gpt4 book ai didi

arrays - C - 避免警告 "address of stack memory associated with local variable returned"

转载 作者:行者123 更新时间:2023-12-02 02:24:52 24 4
gpt4 key购买 nike

我编写了以下简单的程序,对 0 到 9 的数字进行求和:

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

int* allocArray() {
int arr[10];
return arr;
}

int main(void){
int* p;
int summe = 0;
p = allocArray();
for(int i = 0; i != 10; ++i) {
p[i] = i;
}
for(int i = 0; i != 10; ++i) {
summe += p[i];
}
printf("Sum = %d\n", summe);
}

代码编译并提供预期结果“45”。但是我收到以下警告:“与局部变量关联的堆栈内存的地址”‘arr’返回’。我做错了什么?

最佳答案

这是未定义的行为,简单明了。它“起作用”的唯一原因是因为使用这个特定的编译器,堆栈还没有被丢弃,但它是靠借来的时间生存的。

当函数调用完成时,arr 的生命周期立即结束。此后,任何指向 arr 的指针都会失效且无法使用。1

您的编译器使用堆栈内存来存储局部变量,并且警告表明您正在将地址返回到现已失效的堆栈变量。

解决这个问题的唯一方法是动态分配内存并返回:

int* allocArray() {
int* arr = calloc(10, sizeof(int));

return arr;
}

您现在负责稍后释放该内存。

您还可以使用static来延长arr的生​​命周期:

int* allocArray() {
static int arr[10];

return arr;
}

尽管这也不是没有后果,因为现在 arr 是共享的,而不是每个函数调用所独有的。


1 就像 C 语言中的许多事情一样,你“不能做”的事情(因为它们会导致未定义的行为和/或崩溃)和你“可以做”的事情(因为这是被许可的)之间有很大的重叠。语法和编译器。通常您有责任了解您编写的任何代码(无论是暗示的还是其他方式)的后果。

关于arrays - C - 避免警告 "address of stack memory associated with local variable returned",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65848290/

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