user3672051
user3672051

Reputation:

allocating memory for structs

If I have a struct:

typedef struct t_node {
    char* id;
    struct t_node* next;
}TypeNode;

if I have a constructor like this:

void conTypeNode(TypeNode* node, char* id) {
    node = malloc(sizeof(TypeNode));
    node->id = malloc(strlen(id)+1);
    strcpy(node->id, id);
    node->next = NULL;
}

then this code will sig-fault:

void printTypeNode(TypeNode node) {
    printf("%s\n", node.id);
}

int main(int argc, char* argv[]) {
    TypeNode* head = NULL;
    conTypeNode(head, "head");
    printTypeNode(*head); //sig-fault 11: invalid read
}

Could someone explain why this happens? I know that if I change the syntax of conTypeNode to take a double pointer then it works fine. I was thinking maybe it is because malloc will change the address stored in the local variable node but not in the variable head?

Upvotes: 2

Views: 72

Answers (4)

ameyCU
ameyCU

Reputation: 16607

Originaly , in what you do is , copy is created and memory is allocated to that and not to head . So, this is what won't work . return the pointer from function .

What you can do is this -

TypeNode *conTypeNode(char* id) {
   TypeNode *node;
   node = malloc(sizeof(TypeNode));           //allocate memory 
   node->id = malloc(strlen(id)+1);
   strcpy(node->id, id);
   node->next = NULL;
   return node;                               //return pointer
}  

And in main call like this -

head=conTypeNode("head");               

and don't forget to free memory in main.

Upvotes: 0

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12393

In C all functions parameters are passed by value. Even if pointer is passed a called function only gets its value (memory address) and its copy but doesn't get an original pointer so it's not able to modify it. To do what you want you need to pass a pointer to pointer like this:

void conTypeNode(TypeNode** node, char* id) {
    *node = malloc(sizeof(TypeNode));
    (*node)->id = malloc(strlen(id)+1);
    strcpy((*node)->id, id);
    (*node)->next = NULL;
}

   TypeNode* head = NULL;
   conTypeNode(&head, "aaa");

Upvotes: 1

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

void conTypeNode(TypeNode **node, char* id) {
    *node = malloc(sizeof(TypeNode));
    (*node)->id = malloc(strlen(id)+1);
    strcpy((*node)->id, id);
    (*node)->next = NULL;
}

...because you have to return the allocated node.

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67195

Please post code that will compile. Where is node->type declared? Where is your second argument being passed to conTypeNode?

Ata any rate, I can see in main that head is null. Then you dereference head when passing to printTypeNode().

You cannot dereference NULL.

Upvotes: 0

Related Questions