返回指向结构的指针后出现分段错误 [英] Segmentation fault after returning a pointer to a struct

查看:50
本文介绍了返回指向结构的指针后出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有读取文件并返回结构体的程序.

There is program for reading from file and return a struct.

struct ion_bin
{
    int freq;
    long height;
    int amplitude;
};

//Dynamic auto allocating array
typedef struct {
  struct ion_bin *array;
  size_t used;
  size_t size;
} Ionogram;

void freeArray(Ionogram *a); //free memory
void insertArray(Ionogram *a, struct ion_bin element); //realloc memory
void initArray(Ionogram *a, size_t initialSize); //malloc memory

Ionogram* read(int argn, char* argv[])
{
    FILE* stream;
    Ionogram ionogramObj;

    //fill ionogram from file by initArray and insertArray  
    //.....

    return &ionogramObj;
}

int main(int argn, char* argv[])
{
    Ionogram* r = read(argn, argv);

    fprintf(stderr,"Array size: %d Used %d\n",r->size, r->used); //SEGMENTATION FAULT ERROR
    //int second = (*(r->array + 2)).amplitude; //YET SEGMENTATION FAULT ERROR TOO

    //fprintf(stderr, "%d", second);
    return 0;
}

此程序编译成功,但在运行时和调试中通过尝试获取返回结构的字段(在 main 方法中)触发分段错误错误 (SIGSEGV) 如何修复此错误?

This program compile successfully, but in runtime and debug fires segmentation fault error (SIGSEGV) by attempt getting fields of returned struct (in main method) How to fix this error?

推荐答案

你犯了一个初学者的错误,返回了一个指向局部变量的指针.您必须记住,一旦函数返回,局部变量就会超出范围,指向它的指针将变为无效.取消引用这个无效指针会导致未定义行为.

You make a beginners mistake, and return a pointer to a local variable. You got to remember that local variables goes out of scope once the function returns, and the pointers to it will then become invalid. Dereferencing this invalid pointer leads to undefined behavior.

两种可能的解决方案:

  1. 实际上是按值返回一个结构,而不是一个指针.
  2. 使用malloc为结构分配内存,并返回一个指向这个动态分配内存的指针.
  1. Actually return a structure, by value, and not a pointer.
  2. Allocate memory for the structure using malloc, and return a pointer to this dynamically allocated memory.

方法一适用于较小的结构,例如您的结构,但由于必须复制整个结构,因此对于较大的结构效率低下.(不过,这是一个复制,而不是一个深复制.因此,如果结构中有指针,则只会复制指针,而不是它们指向的内容.)

Method one works well for smaller structures, like yours, but become inefficient for larger structures as the whole structure must be copied. (It's a shallow copy though, not a deep copy. So if you have pointers in the structure only the pointers are copied and not what they point to.)

这篇关于返回指向结构的指针后出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆