-5

Here is another question about returning const char * from function.

But I have tried it out with the following codes, it looks like everything works fine.

#include <iostream>
#include <string>

using namespace std;

const char * tocstring(){
    string str = "abcd";
    return str.c_str();
}

int main(){
    const char * p = tocstring();
    cout << p << endl;
    return 0;
}

it will output abcd as what I want. Any idea about this?

Community
  • 1
  • 1
Myzh
  • 23
  • 5
  • 6
    I can't explain it as well as [this post](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794) – Tas Jul 15 '15 at 04:36

3 Answers3

2

it will output abcd as what I want. Any idea about this?

The function tocstring returns a pointer being held by the automatic variable str. The pointer is invalid after the function returns. Your program is subject to undefined behavior. Unfortunately, seemingly sane behavior is a form of undefined behavior.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

You were lucky. tocstring is returning a pointer to memory that has already been freed so this is undefined behavior.

sfjac
  • 7,119
  • 5
  • 45
  • 69
0
const char * tocstring(){                                                                         
    string str = "abcd";                                                                        
    return str.c_str();                                                                          
}

Here str is a local variable. Once it goes out of scope, you should not point it to anymore. It is an UB.

Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68