0

I have function that returns an array of structs. I want to access the value, but I get a segmentation fault.

Minimal reproduction:

#include <stdio.h>

struct example {
    int val;
};

struct example* get() {
    struct example out[1];
    struct example item = {123};
    out[0] = item;
    return out;
}

int main() {

    struct example *items;
    items = get();

    printf("%d\n", items[0].val);

    return 0;
}

It should print 123.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Makalone LOgman
  • 948
  • 1
  • 12
  • 25
  • Do you know when a local variable gets destroyed? – user253751 Aug 28 '20 at 11:26
  • You need to malloc while declaring array. Please check about memory allocation on heap and stack. Local functions like the one you have written is allocating memory on stack, which is then destroyed upon the function exit. – Abhimanyu Shekhawat Aug 28 '20 at 11:32
  • This is because `out` is declared on the stack and it gets destroyed once you exit the function leaving you with a [dangling pointer][1]. You need to allocate your array dynamically so that it only gets destroyed once you `delete` it. [1]: https://en.wikipedia.org/wiki/Dangling_pointer – Jacob Krieg Aug 28 '20 at 11:33
  • Okay will research, thanks – Makalone LOgman Aug 28 '20 at 11:34

0 Answers0