Weird memory assignments

Jun 27, 2014 at 4:39pm
Hi, I was writing a program and ran into something I really dont understand..
Does anyone know why the 'temp' variable inside the constructor has the same address as the 'bloc' variable in the main fucntion? I would think me.date would hold "No date", but apparently it was overwritten with "sfnysng".
Maybe I'm missing something.
Thanks


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

#include <iostream>
using std::cout;
using std::endl;
using std::string;

class data
{
public:
    char * date;
    data()
    {
        string temp = "No Date";
        cout<<&temp<<endl;
        date = (char*)temp.c_str();
    }
};
data me;
int main()
{
    string bloc = "sfnysng";
    cout<< me.date <<endl;
    cout<< &bloc;
    return 0;
}


output:

0x28fea8
sfnysng
0x28fef8

EDIT: I just noticed the slight difference in address. But that makes even less sense; why is the value of bloc being put into me.date?
Last edited on Jun 27, 2014 at 4:42pm
Jun 27, 2014 at 5:13pm
Since temp is a temporary variable, it is destroyed when it goes out of scope at the closing brace on line 16. The memory it used can now be re-used for any purpose, thus the address stored in the pointer date is no longer valid.
Jun 27, 2014 at 5:21pm
Construction of me begins before main is executed. String temp is allocated. It allocates some storage in heap where it stores its content. You are assigning pointer to that inplementation data in date. Then it is destroyed and date pointer is left hanging.

Next main() is executed. bloc is created. It allocates some memory to store its line, and your compiler just happens to allocate memory which was just deallocated. So to simplify it took room what temp was using before.

Even same address would be explainable because temp was created on stack which is heavily reused. The difference between pointers is probably because of other data program uses internally.

Using dangling ponter is UB and you should not be surprised if your program will blow your PC.

Jun 27, 2014 at 5:22pm
Oohh. Ok, thanks
Topic archived. No new replies allowed.