【问题标题】:Segmentation fault when returning pointers [duplicate]返回指针时出现分段错误[重复]
【发布时间】: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


【解决方案1】:
int* add(int* a,int* b)
{
        //a and b are pointers to integers
        int c=(*a)+(*b);
        return &c;
}

这是一个糟糕的方法,因为在返回函数后,局部变量c 的位置不能保证它指向一个有效的地址。

因此,您应该使用malloc/calloc 函数或将c 设为静态变量。

【讨论】:

  • 使c static 可以解决问题,但这种方法也很糟糕。这里最好的方法是不返回结果的地址而只返回结果:int add(int *a, int *b) {return *a + *b;} 甚至更好的int add(int a, int b) {return a + b;}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 1970-01-01
  • 2018-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多