0

My code is as follows:

#include "stdio.h"
#include "string.h"
struct ABC {
    char name[20];
    int n; 
};
struct ABC& myfun(void) {
    struct ABC
    x ={ "Lining",99 };
    return x;
}
int main(void) {
    struct ABC y = myfun();
    printf("%s %d\n", y.name, y.n);
    return 0;
}

Here I called myfun(), which returns a reference to a local struct ABC variable. This should be wrong because after myfun() returns, the memory it used will no longer serve. But this code runs well in VS2015 and print correct information as "Lining 99".

Why can I get this outcome?

Kun Wu
  • 139
  • 6

2 Answers2

2

The destructor for a POD type like your struct ABC is likely a no-op.

It's wrong to do what you're doing, but it happens to work because destruction doesn't do anything; the data will be lost when it's overridden due to the stack growing back over it, but the memory with the same data is still there until then. Don't rely on this (you already know it's wrong), but it's doing exactly what you expect, copying from the (now relinquished) stack frame of the called function before it gets overwritten by subsequent calls.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

According to the C++ Standard, the function:

struct ABC& myfun(void) {
    struct ABC
    x ={ "Lining",99 };
    return x;
}

is legal. It would only be undefined behaviour if another function calls this function and tries to use the result. The compiler is not allowed to reject a program that doesn't try to use the result.

In fact the program can only be rejected if the compiler can prove that execution always reaches the attempt to use the result. For your particular program the compiler could do that but the compiler writers chose not to perform that particular analysis.

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
M.M
  • 138,810
  • 21
  • 208
  • 365