James Real James Real - 18 days ago 6
C Question

C programming. Pointers to struct

This is my first post. I'm very confused with the C's pointer and its relation to struct. I've searched for more information but can't really conclude them. For example given this struct definition

typedef struct node
{
int info;
struct node *next;
}NODE;


Then what's the differences and effects of these four declarations;

1. NODE *node1 = malloc (sizeof(NODE));
2. NODE *node1 = (struct node *) malloc (sizeof(NODE));
3. NODE *node1 = (struct node *) malloc (sizeof(NODE *));
4. NODE *node1 = malloc (sizeof(NODE *));


Thanks in advance.

Answer

These are equivalent and allocate a block of memory the same size as a NODE struct.

1. NODE *node1 = malloc (sizeof(NODE));
2. NODE *node1 = (struct node *) malloc (sizeof(NODE));

These are just wrong

3. NODE *node1 = (struct node *) malloc (sizeof(NODE *));
4. NODE *node1 = malloc (sizeof(NODE *));

Line 3 allocates a memory block the size of a pointer to a NODE structure. The cast allows you to assign it without any errors being thrown, and possibly without warnings. But it's not what you want.

Line 4 does the same as line 3. malloc returns a void * which doesn't require casting, but a good static analyzer should give you a warning.

Either way, lines 3 & 4 are recipes for buffer overflows and undefined behavior.

Lines 3 and four would be correct if written thus:

NODE **ptr = malloc(sizeof(NODE *));