簡體   English   中英

在結構中取消對指針的引用時出現段錯誤

[英]Segfault when dereferencing pointer to pointer within struct

我有一個結構,其中包含一個指向指針的指針作為其成員之一。 嘗試取消引用此指針時,我一直遇到段錯誤。

person_init創建一個人,並為其命名(約翰)。 名稱是指向字符串的指針。 我可以在此函數中使用printf()沒問題。 返回main()函數,再次可以將printf()命名為沒有問題。 但是,當我輸入一個新函數並嘗試printf()我遇到了段錯誤。 我真的很困惑,因為我很確定name是在堆上分配的。

我在這里想念什么?

碼:

#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 */
}

這是問題所在:

newp->name = &name;

newp->name現在指向name ,這是person_init的局部變量。 一旦person_init返回, name就消失了,而newp->name是無效的指針。 之后再嘗試使用它都會導致未定義的行為。

固定:

struct person {
    char *name;
};

並將其初始化為

newp->name = name;

現在newp->name是副本name ,即它指向分配的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM