【发布时间】:2021-12-22 00:19:00
【问题描述】:
我最近开始学习C,这段代码出现了一个问题:
#include <stdio.h>
#include <stdlib.h>
int* add(int* a,int* b)
{
//a and b are pointers to integers
int c=(*a)+(*b);
return &c;
}
int main()
{
int x=2,y=4;
int* z=add(&x,&y); //call by reference
printf("sum=%d\n", *z);
return 0;
}
这应该可以在windows机器上运行,但是当我编译它时,出现了这个问题:
gcc -o hello return.c
return.c: In function ‘add’:
return.c:8:9: warning: function returns address of local variable [-Wreturn-local-addr]
8 | return &c;
| ^~
./hello
Segmentation fault (core dumped)
This post 描述了这里发生的事情,但在我一直关注的教程中的 windows 机器上并没有发生,我朋友的 windows 机器也可以运行它。有没有办法我可以模仿这种行为在 gcc 编译器上?
另外,有人可以解释为什么错误不会在 Windows 中发生吗?堆栈帧在被销毁后,据我所知,不应允许再次访问该地址,那么为什么不能将其用于基于 DOS 的系统?
【问题讨论】:
-
返回悬空指针(指向局部变量的指针)不是编译错误。它只是调用未定义的行为。这意味着从那时起,任何事情都可能发生,从预期结果到意外结果导致程序崩溃。在现实世界中,它取决于没人愿意关心的实现细节。规则就是不要。
-
“另外,有人能解释一下为什么这个错误不会在 Windows 中发生吗?”查看链接的副本以及What is undefined behavior and how does it work?
标签: c pointers gcc segmentation-fault