I have made this simple test program:
#include <iostream>
class test {
public:
void print() {
std::cout<<"hello world!"<<std::endl;
}
};
test* getPointer1() {
return new test;
}
test* getPointer2() {
test a;
return &a;
}
int main() {
test* test1;
test* test2;
test1=getPointer1();
test2=getPointer2();
test1->print();
test2->print();
}
For what i know, when you return a pointer to a memory location, and the function ends, the pointer should point to a portion of memory that no longer exists. But i don't seem to be right: when you call test1->print()
and test2->print()
, istead of getting a segmentation fault, the program prints two time hello world!
.
Could you explain me why this occur?
Thank you in advice and sorry for my bad english