简体   繁体   中英

Segfault when dereferencing pointer to pointer within struct

I have a structure which includes a pointer to a pointer as one of its members. I keep getting a segfault when trying to dereference this pointer.

Create a person in person_init and give it a name (John). Name is a pointer to a character string. I can printf() no problem in this function. Returning to the main() function, again I can printf() the name no problem. But then when I enter a new function and try to printf() I get a segfault. I'm really confused because I'm pretty sure name is being allocated on the heap.

What am I missing here?

code:

#include <stdio.h>
#include <stdlib.h>

/* structure with a pointer to pointer member */
struct person {
    char **name;
};


/* allocate space for the strucutre */
int person_init(struct person **p)
{
    struct person *newp = malloc(sizeof(struct person));

    /* give a name, allocated on the heap */
    char *name = malloc(sizeof(char) * 5);
    *name = 'J';
    *(name + 1) = 'o';
    *(name + 2) = 'h';
    *(name + 3) = 'n';
    *(name + 4) = '\0';
    newp->name = &name;
    *p = newp;

    printf("Name in init: %s\n", *(*p)->name); /* this works */

    return 0;
}


void print_name(struct person *p)
{
    printf(*p->name);
}


int main()
{
    struct person *person;
    person_init(&person);
    printf("Name in main: %s\n", *person->name);   /* works */
    print_name(person);                            /* segfault */
}

Here's the problem:

newp->name = &name;

newp->name now points to name , which is a local variable in person_init . As soon as person_init returns, name is gone and newp->name is an invalid pointer. Any attempt to use it afterwards results in undefined behavior.

Fix:

struct person {
    char *name;
};

And initialize it as

newp->name = name;

Now newp->name is a copy of name , ie it points to the allocated string.

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