4

Here is my program

 int* fun1(void)
 {
    int n=9;
    int *pf=&n;
    cout<<*pf<<endl;
    return pf;
 }
 int main(int argc, char *argv[])
 {
    int *p=fun1();
    cout<<*p;
    return 0;
 }

Compilation and running of program doesn't give any problems but with valgrind it gives message/warning "Invalid read of size 4".

Any help to resolve the warning is most welcome

Santosh Sahu
  • 2,134
  • 6
  • 27
  • 51
  • 10
    You are returning a pointer to a local variable, then de-referencing it. That is undefined behaviout. – juanchopanza Nov 05 '13 at 09:37
  • 1
    n is only defined inside the scope of fun1. The reason it seems to work is because the stack hasn't been overwritten by anything new. Try calling some functions between your assignment of *p and printing it to see what happens. – SBI Nov 05 '13 at 09:38
  • Fixing the code to no longer invoke undefined behavior will have the effect on valgrind's warning emission that you seek. – WhozCraig Nov 05 '13 at 09:39
  • Have you enabled compiler warnings? You shouldn't need to go as far as dynamic analysis to catch this error. – Mike Seymour Nov 05 '13 at 10:34

4 Answers4

4

nis a local variable in fun1() and is no more valid after exit of the function.

Axel
  • 13,939
  • 5
  • 50
  • 79
1

Local variables exists only when the function is active. You're returning pf which is a pointer to a local variable. As soon as you exit the function, the memory that was allocated to the variable is deallocated, this leads to undefined behavior.

lepe
  • 24,677
  • 9
  • 99
  • 108
Maroun
  • 94,125
  • 30
  • 188
  • 241
1

Turning my comment into an answer: You are referencing a local variable from outside of a function after that function has returned. This means that even though, while running the program this seems to work because the stack stays untouched between the assignment. If you call other functions between the assignment and the print, it will most likely fail. I say "most likely" because what you're doing is undefined behavior, and can therefor not be predicted.

To fix this particular case: allocate memory for n on the heap inside fun1, and return a pointer to said memory instead of what you have now.

SBI
  • 2,322
  • 1
  • 17
  • 17
0

You are returning an address of a local variable and valgrind is warning you of that. Accessing this pointer in the main will invoke undefined behavior.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176