0
#include<stdio.h>

struct Node {
    int a;
};

struct Node* prepare() {
    struct Node node = { 123456 };
    return &node;
}

int main() {
    struct Node* node = prepare();
    printf("%d\n", node->a);
    printf("%d\n", node->a);
    return 0;
}

following is the result

enter image description here

so why the results are different?

Simson
  • 3,373
  • 2
  • 24
  • 38
映宏李
  • 1
  • 1
  • 4
    Local variables are no longer valid once the function exits. Using the address of such a variable outside the function is undefined behaviour. – kaylum May 04 '20 at 04:20
  • 2
    Any decent compiler should be able to detect this problem and issue a warning. If you don't get any warning, then please increase warning levels. – Some programmer dude May 04 '20 at 04:22

1 Answers1

0

prepare is returning a pointer to memory block, a local variable allocated on the stack. The memory block is reused by the system after return. When you print it the second time the memory block have been overwritten.

Simson
  • 3,373
  • 2
  • 24
  • 38
  • thanks , I know it but I forgot the principle in this code, when I understand and I realized how simple the question I ask. – 映宏李 May 04 '20 at 04:37