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
#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?
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.
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.