[英]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). 在person_init
创建一个人,并为其命名(约翰)。 Name is a pointer to a character string. 名称是指向字符串的指针。 I can printf()
no problem in this function. 我可以在此函数中使用printf()
没问题。 Returning to the main()
function, again I can printf()
the name no problem. 返回main()
函数,再次可以将printf()
命名为没有问题。 But then when I enter a new function and try to printf()
I get a segfault. 但是,当我输入一个新函数并尝试printf()
我遇到了段错误。 I'm really confused because I'm pretty sure name
is being allocated on the heap. 我真的很困惑,因为我很确定name
是在堆上分配的。
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
. newp->name
现在指向name
,这是person_init
的局部变量。 As soon as person_init
returns, name
is gone and newp->name
is an invalid pointer. 一旦person_init
返回, name
就消失了,而newp->name
是无效的指针。 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. 现在newp->name
是副本name
,即它指向分配的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.