简体   繁体   中英

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 ?

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.

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");

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM