Automatic Storage within Scope

Hi there,

I encountered a funny problem and don't know what to make of it. The following code allows to print the correct name in the main function which was entered in *getname()!! Thats weird because the char array and the pointer should be deleted after the function ends. What makes me wonder even more is: when the name gets written directly into the derefrenced pointer (cin >> *p_name //line27) and line 31 is left away. The name is no longer available in main.

The change in lines 27 and 31 should not have an effect on the outputting string in main, or am I missing something?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

#include <iostream>
#include <cstring>

using namespace std;

char *getname(void); //function prototype

int main(){
    char *p_name;

    p_name = getname();
    cout << p_name << " at " << (int*)p_name << "\n";
    delete [] p_name;

    p_name = getname(); //reuse freed memory
    cout << p_name << " at " << (int*)p_name << endl;
    delete [] p_name;

    return 0;
}

char *getname() {
    char temp[80];  //dies away after function ends
    char *p_tester = temp; //dies away after function ends
    cout << "Enter last name: ";
    cin >> temp;
        //  char *pn = new char[strlen(temp) + 1];
        //  strcpy(pn, temp);
        //  p_tester = temp;
    p_tester = temp;

    return p_tester;
}


thanks a lot for the help ;)
cheers
I simply say that the code has undefined behavior.
hey vlad, ok thanks, i thought that maybe it is compiler dependent or that i am missing sth. But undefined sounds good.
There's a famous SO post about this http://stackoverflow.com/a/6445794/273767
Topic archived. No new replies allowed.