1

Possible Duplicate:
Pointer to local variable

#include <iostream>
using namespace std;

char* func();

int main() {
    char* str;
    str = func();
    cout<<str;
    return 0;
}

char*  func() {
    char * str;
    char p[] = "priyanka is a good girl";
    str = p;
    cout<<str<<"\n";
    return str;
}

gives the output,

priyanka is a good girl

priy

I did not understand what just happened here, why an incomplete array was given as output. I am a little new with this. Please help.

Community
  • 1
  • 1
priyanka
  • 13
  • 2

2 Answers2

4

Your function func() returns a pointer to a local variable, which later causes undefined behaviour when you try to access it.

FailedDev
  • 26,680
  • 9
  • 53
  • 73
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • oh yes, sending a pointer to local variable doesn't make any sense :P. thanks – priyanka Nov 08 '12 at 19:05
  • I'd add that it's allocated on the stack. When the function returns, its stack frame (where the pointer points to) is deallocated, which is why you can get a partially correct/jumbled output, when some but not all of the old stack frame has been reused by something else. – GraphicsMuncher Nov 08 '12 at 19:13
1

In func2() char p[] is a local variable initialized on stack. Returning a pointer to stack variable is a bad idea(and is undefined behaviour as well), and I think your string "priyanka is a good girl" got overwritten when the function returned.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78