1

I have some doubt regarding what the size of a self referential structure in C is. I ran the following code and it gave me a output of 24

#include<stdio.h>

int main() {

    struct hello {      
        int a;
        char ch[10];
        struct hello *p;
    } dhiraj;

    printf("%d",sizeof(struct hello));
    return 0;
}

Now next I modified the index of ch and made it 20 the next time and after running it gave on output of 32

The other weird behavior which I noted was that after the execution of the following code -

#include<stdio.h>

int main() {

    struct hello {
        int a;
        // int b; Statement 1 
        // int c; Statement 2
        struct hello *p;
    } dhiraj;

    printf("%d",sizeof(struct hello));
    return 0;
}

I got an output of 16. After activating statement 1 the output was still 16 but after activating both statement 1 and statement 2 the output became 24. What is actually happening here ?

mkj
  • 2,761
  • 5
  • 24
  • 28
Dhiraj Barnwal
  • 180
  • 2
  • 15

2 Answers2

2

What you're running into is data structure padding. Data is handled in word size chunks, on a 64 bit computer this is probably 8 bytes. This means your structs will be padded to a multiple of 8.

struct hello {
    int a;
    char ch[10];
    struct hello *p;
}

Assuming you're on a 64 bit machine with 64 bit pointers, that is 4 + 10 + 8 = 22. 22 isn't a multiple of 8, so sizeof(struct hello) gets padded out to 24. Change it to ch[12] and you'll still get 24. Change it to ch[13] and the size will jump to 32.

This is a bit oversimplified, but you get the idea.

Schwern
  • 153,029
  • 25
  • 195
  • 336
1

Short version: the allocated needs to allocate in blocks of 8 bytes.

So the maths goes like this on a 64bit architecture. a pointer is going to be 8 bytes so that will be the size of : struct hello *p;

The size of the int is gonna be 4 bytes since its a 32 bit integer.

A struct content both of these will be 12 - but since this the word size of the machine is 64 bits compiler will allocate a full number of words(8 bytes each) .. making 16 the smallest option - adding another integer(int a) if free since it can still fit in the 16 bytes. but the second integer mean that you have to use another word to fit the full payload.

Martin Kristiansen
  • 9,875
  • 10
  • 51
  • 83