返回指针时出现分段错误
Segmentation fault when returning pointers
我最近开始学习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机器可以运行 它 too.Is 我可以在 gcc 编译器上模拟这种行为吗?
此外,有人可以解释为什么 windows 中没有发生错误吗?根据我的理解,堆栈帧在被销毁后不应允许再次访问该地址,那么为什么这不会在基于 DOS 的系统上继续存在?
int* add(int* a,int* b)
{
//a and b are pointers to integers
int c=(*a)+(*b);
return &c;
}
这是一个糟糕的方法,因为在返回函数后,不能保证局部变量 c
的位置指向有效地址。
因此,您应该使用 malloc
/calloc
函数或创建 c
静态变量。
我最近开始学习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机器可以运行 它 too.Is 我可以在 gcc 编译器上模拟这种行为吗?
此外,有人可以解释为什么 windows 中没有发生错误吗?根据我的理解,堆栈帧在被销毁后不应允许再次访问该地址,那么为什么这不会在基于 DOS 的系统上继续存在?
int* add(int* a,int* b)
{
//a and b are pointers to integers
int c=(*a)+(*b);
return &c;
}
这是一个糟糕的方法,因为在返回函数后,不能保证局部变量 c
的位置指向有效地址。
因此,您应该使用 malloc
/calloc
函数或创建 c
静态变量。