gpt4 book ai didi

c - 为什么这个 C 函数有副作用?

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:42 25 4
gpt4 key购买 nike

有人能帮我理解这个 C 程序有什么问题吗?

#include <stdio.h>
#include <stdlib.h>
struct Box {
int **value;
};
void nop(void) {
/* Why does this function have side effects? */
void *a = malloc(sizeof *a);
free(a);
}
struct Box *makeBox(void) {
int *value = NULL;
struct Box *box = malloc(sizeof *box);
box->value = &value;
return box;
}
int main(void) {
struct Box *box = makeBox();
printf("Dereferenced: %p\n", *box->value);
nop();
printf("Dereferenced: %p\n", *box->value);
}

如果我运行它,它会打印:

Dereferenced: (nil)
Dereferenced: 0x562831863727

但是,如果我注释掉 nop 函数,我会得到:

Dereferenced: (nil)
Dereferenced: (nil)

谁能帮我理解为什么调用 nop 会改变 *box->value

最佳答案

基本上 nop() 函数具有“副作用”,这是使用堆栈的结果。问题出在 makeBox() 函数中,它设置了一个指向堆栈变量的指针。我在片段中添加了一些评论:

struct Box *makeBox(void) {
// value is an integer pointer on the stack
int *value = NULL;
struct Box *box = malloc(sizeof *box);
// box->value is set to the address of the stack location of value
box->value = &value;
return box;
}

nop() 在堆栈上分配 a 时,它实际上是踩踏另一个指针所在的堆栈。这是为什么不能返回指向堆栈变量的指针的示例,因为它不会在分配它的函数范围之外持续存在。

关于c - 为什么这个 C 函数有副作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50262919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com