On the stack, memory is reserved for main , which we call the frame stack for the main function.
When we call the Add function, memory is allocated over the stack. In the stack frame of the Add functions, a and b are local pointers, and c is an integer that calculates the sum and then returns the link. c is the local variable of the Add function.
Now that the Add function has completed, the memory space on the stack is also freed, so when we try to access this address in main with a pointer p , what we are trying to get is basically freed space. The compiler gives a warning, but why is it still printing the value 5 correctly?
The answer to this question may lie in the fact that the machine did not free the memory space, because it did not consider it necessary, since there were no more functions. But if we write another Hello function, then it should definitely free up space for the Add function in the call stack, but the program still prints
Yay 5
This is because, as in the heap, we need to assign a pointer to null after it is released, otherwise we can still access it? Is there something similar here?
int* Add(int *a,int *b) { int c=*a+*b; return &c; } int main() { int a=1,b=4; int *p=Add(&a,&b);
Stack source share