【发布时间】:2020-10-08 13:07:43
【问题描述】:
错误:
在将双指针传递给函数时,指针指向的字段的值似乎取决于函数的某些局部变量。
更具体地说,当我评论 L 行时(在函数“函数”中)
输出:
In the main function: 1
In the function: 1
但是当我取消注释同一行时,
输出:
In the main function: 1
In the function: 0
程序:
typedef struct s{
int *value;
}s;
s** initialize()
{
s** temp = (s**)malloc(sizeof(s*));
s* f = (s*)malloc(sizeof(s));
f->value = NULL;
temp = &f;
return temp;
}
void function(s** what)
{
//Line L: size_t count = 0;
printf("In the function: %d\n", (*what)->value == NULL);
}
int main()
{
s** m = initialize();
printf("In the main function: %d\n", (*m)->value == NULL);
function(m);
}
我尝试过的:
- 我以为我得到的是随机输出,但事实并非如此,因为我一直得到相同的输出。
- 我尝试破译汇编语言代码,但这对我来说太神秘了。
环境:
- 编译器:
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
- 操作系统:linux mint
【问题讨论】:
-
temp = &f;->*temp = f: -
@SouravGhosh RobertS 对此发表了非常好的声明,请参见此处:stackoverflow.com/a/62351067/12139179
-
@Ctx 答案属于 meta
-
@AndrasDeak 我不同意,当提出这个问题时,它就属于可以阅读的地方。
标签: c pointers memory-leaks undefined-behavior dereference