Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of a pointer pointing to a structure [duplicate]

I was trying to remember the basics of C programming, and regarding pointers to structures I was doing the following:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

int main()
{
    struct MyStruct {
        int number;
        char *name;
    };

    int i;

    struct MyStruct *p_struct = (struct MyStruct *) malloc(sizeof(struct MyStruct)*3);
    printf("sizeof(struct MyStruct) = %d\n", sizeof(struct MyStruct));

    for (i = 0; i < 3; i++)
    {
        p_struct->number = i;
        p_struct->name = "string";
        printf("p_struct->number = %d, p_struct->name = %s\n", p_struct->number, p_struct->name);
        ++p_struct;
    }

    printf("sizeof(p_struct) = %d\n", sizeof(p_struct));
    free(p_struct);
    return 0;
}

My question is: I get 8 bytes as the size of the structure, which is okay as 4+4 = 8 bytes due to alignment/padding of the compiler, but why do I get 4 bytes from sizeof(p_struct)?

I was expecting to get 24 (8 bytes x 3), why is this so?

If this is correct, can I get the total allocated size of 24 bytes somehow?

like image 948
c_b Avatar asked May 20 '14 13:05

c_b


2 Answers

No, the size of the structure is eight bytes because you have two four-byte fields in it, try printing sizeof(int) and sizeof(char *) and see for yourself.

When you do sizeof of a pointer, you always gets the size of the pointer and never what it points to. There is no way (in standard C) to get the size of memory you have allocated with malloc.

Also note that you have undefined behavior in your code, as you change the pointer p_struct so it no longer points to what your malloc call returned. This leads to the undefined behavior when you try to free that memory.

like image 74
Some programmer dude Avatar answered Sep 19 '22 12:09

Some programmer dude


Pointers are always the same size on a system no matter what they're pointing to (int, char, struct, etc..); in your case the pointer size is 4 bytes.

like image 25
Clinton Pierce Avatar answered Sep 20 '22 12:09

Clinton Pierce