1
#include<stdio.h>

int* add(int *a, int *b){
    int c = *a + *b ;
    return &c;
}

int main(void) {
    int a=3,b=2 ;
    int *ptr = add(&a,&b); // doubt in this line as it returns 5

    printf("%d",*ptr);
}

I have doubt in the line commented.

I am using Codeblocks IDE(GNU gcc compiler), and I was wondering that if the *ptr in my main is pointing to the address of c in the add function, then it should print garbage as after the function `add completes its execution, it's popped from the stack, and the memory should be deallocated for it in the stack . So technically, it should be pointing to garbage. Then how is it printing the correct value.

fluter
  • 13,238
  • 8
  • 62
  • 100
Spandan
  • 31
  • 7
  • 3
    “it should print garbage as after the function `add completes its execution” Although it is for a different language, your question is entirely answered by http://stackoverflow.com/a/6445794/139746 – Pascal Cuoq Nov 26 '16 at 02:15

2 Answers2

2

You have undefined behavior, as you are returning the address of a function-local variable. A good compiler with warnings enabled would tell you this.

When you have undefined behavior you don't get to complain about the results. There is no need to wonder why it gives you the "correct" result because it does not--it gives you some number which may or may not be correct depending on any number of factors you don't control.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Was wondering the same whether it's compiler oriented or not . But still the function returning the exact answer was what seemed odd to me . thanks – Spandan Nov 26 '16 at 02:16
  • 1
    @AuSm88: Undefined behavior means all such questions are moot. It's undefined behavior under the language standard, regardless of which compiler you use. The code is simply invalid. If one particular compiler gives you the "correct" answer on Monday, it may still give a different answer on Tuesday. – John Zwinck Nov 26 '16 at 02:19
  • yeah agree on that . :) – Spandan Nov 26 '16 at 02:22
2

I think this is undefined behavior. On my system this example crashed with a segmentation fault. When something is deallocated, it is possible that the pointer to that memory location is simply moved without zeroing out the memory.

Byte
  • 509
  • 6
  • 15
  • 2
    This is the best explanation for why the OP is repeatedly seeing the same value over and over again. A naive C compiler that does no optimization whatsoever very likely builds a stack frame and simply moves the stack and frame pointer variables, as you say, without touching the memory in any way. It's still technically garbage from the point of the semantics, as you note. – Ray Toal Nov 26 '16 at 02:16
  • I see . That clears some things up . Thanks mate – Spandan Nov 26 '16 at 02:18
  • Glad I could help. I guessed this was the issue because this is how Forth deallocates from its dictionary as well. – Byte Nov 26 '16 at 02:21