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.
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 *));
// node1 is a pointer to (heap) memory block of size NODE
1. NODE *node1 = malloc (sizeof(NODE));
// same as 1. (but 1. is the preferred way)
2. NODE *node1 = (struct node *) malloc (sizeof(NODE));
// (Wrong) node1 is a pointer to (heap) memory block of size pointer to NODE (a pointer to _usually_ 4 bytes)
// but you cast it to pointer to NODE (a pointer to more than 4 bytes)
3. NODE *node1 = (struct node *) malloc (sizeof(NODE *));
// (Wrong) same as 3
4. NODE *node1 = malloc (sizeof(NODE *));
Stick with number 1. as it's the common way to allocate an object in the heap (dynamic allocation): Object *object = malloc(sizeof(Object)). You can forget about 2. 3. 4. which complicate the issue and really not what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With