This following code works fine:
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct node{
int a, b, c, d, e;
};
struct node *ptr = NULL;
printf("Size of pointer ptr is %lu bytes\n",sizeof (ptr));
printf("Size of struct node is %lu bytes\n",sizeof (struct node));
ptr = (struct node*)malloc(sizeof (ptr)); //Line 1
// ptr = (struct node*)malloc(sizeof (struct node)); //Line 2
ptr->a = 1; ptr->b = 2; ptr->c = 3; ptr->d = 4; ptr->e = 5;
printf("a: %d, b: %d, c: %d, d: %d, e: %d\n",
ptr->a,ptr->b,ptr->c,ptr->d,ptr->e);
return 0;
}
When complied as:
gcc -Wall file.c
My question is: why is this fine?
malloc allocates the number of bytes which are specified in it’s argument. Here sizeof ptr is 8 bytes on my 64-bit linux machine. I thought malloc will provide 8 bytes but then how is it accessing all the variables a,b,c,d,e? Is it with gcc only or am I missing something with standard C?
As far as I know “Line 2” should be there instead of “Line 1” but either of the line works fine. Why?
You have undefined behavior here.
mallocwill allocate 8 bytes (as you say), but this cast is “bad”:After this line,
ptrwill point to a memory block, which has only 8 allocated bytes, the rest are some “random” bytes. So, makingyou actually change some memory, not only the allocated by
malloc.In other words, you are rewriting memory, you’re not supposed to touch.