Search code examples
cpointersstructuresizeof

How can i identify the size of structure member?


struct busData{
int busNum;
char str[SIZE+1]; //SIZE  = 1000
};

int main(){
    struct busData *bus = (struct busData*)calloc(5, sizeof(struct busData));


printf("\n%d", sizeof(bus)); //result is 4
free(bus);    
return 0;
    }

Now It is showing '4' or '8'depending on platform as a result. I think it should display 5040 right? Because I gave 5 value with calloc(). So how can I get 5040? i am using the 3 elements until 'bus+2' and then I am freeing up with free(bus); And i want to know how many elements left (it should show 2008). so i need 5040?


Solution

  • I think the code is screwed up from the beginning. The problem with sizeof was already explained in other answers.

    Another big problem is this:

    Because I gave 5 value with calloc(). So how can I get 5040? i am using the 3 elements until 'bus+2' and then I am freeing up with free(bus); And i want to know how many elements left (it should show 2008). so i need 5040?

    This sounds like you want to use the remaining 2 elemens after calling free.

    First:

    you have 1 pointer. The compiler can tell you the size of the pointer and the size of the single element that the pointer is pointing to. The compiler has no idea that you allocated memory for more than 1 element of that type and hence cannot tell you anything different than size of pointer or size of 1 element.

    Second:

    There is no concept like "using" some memory. For the compiler and the OS it doesn't matter if you write something to the memory location or not. It doesn't care if some bytes are still (or again) filled with 0.

    Third:

    If you allocate a block of memory and free it again, the whole block is free'd and mustn't be used any longer. If you expect to have 2008 bytes that you still can use, you are wrong! Your pointer will point to an invalid address after free is called. Using that pointer to access the memory afterwards is undefined behaviour