Roma  Karageorgievich Roma Karageorgievich - 2 months ago 12
C Question

Sizeof pointer in structure in C

I have such structure:

struct node{
int key;
int data;
struct node *next;
};


Then I created
link
:

struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = 10;
link->data = 100;
link->next = link;


When I want to find out the size of each element I do:

printf("%zd %zd %zd %zd\n", sizeof(link->key), sizeof(link->data), sizeof(link->next), sizeof(link));


And as output I have:

4 4 8 8


So, the first question is why
sizeof(link)
doesn't include
sizeof(link->next)
?

The second question is:
When I try to
free
allocated memory of
link
:

printf("Size of link is %zd\n", sizeof(link));
free(link);
printf("Now size of link is %zd\n", sizeof(link));


I have:

Size of link is 8
Now size of link is 8


Why didn't freeing of memory happen?

Answer

So, the first question is why sizeof(link) doesn't include sizeof(link->next)?

Because link is a pointer. If you print sizeof(*link), you would get a different number.

Why didn't freeing of memory happen?

Freeing memory does happen. It's just that it cannot be measured the way that you try it, i.e. with sizeof. The size remains the same regardless of whether the pointer points to something valid or to something invalid.