0

I have a function that returns a pointer to a custom struct I made:

struct CustomStruct * function1() {
    // other stuff before this ... 
    struct CustomStruct cs = {param1, param2, param3};
    struct CustomStruct *cs_p = &cs;
    return cs_p;

then another function using the return value of this function:

void function2() {
    struct CustomStruct *new_cs_p = function1();

but if I try printing the values in new_cs_p I get weird characters. They print fine in function1 before I return them. Any idea as to what's causing this?

itsmewiththeface
  • 190
  • 1
  • 4
  • 12
  • The solutions proposed in the possible duplicate are in C++. There is no `new` keyword in C. I tried malloc'ing the variable before calling the function which didn't help either. – itsmewiththeface Aug 04 '18 at 01:12
  • 2
    Perhaps you're looking at a different question, but [the linked one I'm seeing](https://stackoverflow.com/questions/1475635/returning-pointer-to-a-local-structure) is in C, and it should answer your question. I'd also recommend reading [this question and its answers](https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap). – tonysdg Aug 04 '18 at 01:23

0 Answers0