minhvnqh
minhvnqh

Reputation: 21

Do I need to call malloc() for other field in a struct after calling malloc for that struct itself?

Let say I have a type node_t

typedef struct node{
    char* value;
    struct node *next;
}node_t;

When I want to create a new node_t pointer named n1, I call malloc

node_t *n1 = malloc(sizeof(node_t));

Now I want to access and use other fields inside n1 : value and next, do I have to call malloc for these pointer again, like this:

n1->value = malloc(sizeof(char));
n1->next = malloc(sizeof(node_t));

Or the very first calling malloc() when creating n1 have already do all these thing ?

Upvotes: 2

Views: 91

Answers (1)

4386427
4386427

Reputation: 44274

do I have to call malloc for these pointer again

It depends on how you want to use those members.

When you malloc a node_t you get memory for storing 1) a char pointer and 2) a node_t pointer. You can set these pointers to point to other existing objects. But you can also set these pointers to point to new (dynamic allocated) objects.

Example 1

node_t *n1 = malloc(sizeof *n1);
assert(n1 != NULL);
n1->value = "Hello world";
n1->next = NULL;

node_t *n2 = malloc(sizeof *n2);
assert(n2 != NULL);
n2->value = "Have fun";
n2->next = NULL;

n1->next = n2;  // Create a linked list

In this example there is no direct malloc for any members of node_t. The members are just set to point to other objects.

Example 2

node_t *n1 = malloc(sizeof *n1);
assert(n1 != NULL);
n1->value = "Hello world";

n1->next = malloc(sizeof *n1->next);
assert(n1->next != NULL);
n1->next->value = "Have fun";
n1->next->next = NULL;

This example results in the same as the first example. It's just written a little different, i.e. the next pointer of n1 is assigned to point to a new malloc'ed node_t instead of having a n2 object.

Example 3

char *str1= "Hello world";
char *str2= "Have fun";

node_t *n1 = malloc(sizeof *n1);
assert(n1 != NULL);
n1->value = malloc(1 + strlen(str1));
strcpy(n1->value, str1);  // Copy the string

n1->next = malloc(sizeof *n1->next);
assert(n1->next != NULL);
n1->next->value = malloc(1 + strlen(str2));
strcpy(n1->next->value, str2);  // Copy the string
n1->next->next = NULL;

Here the value pointer is set to point to a new malloc'ed object and a copy of a string is placed in that object.

So - to repeat - whether you want to malloc memory for the members depends on how you want to use the struct.

Upvotes: 2

Related Questions