So this is a implementation of a simple class A which has public int variable x assigned to 10. I am then creating a pointer to A and calling the run() function which prints the integer x and a string. Then after deleting the pointer I am calling the run() function again.
My code:
#include <iostream>
class A {
public:
A() = default;
~A() = default;
int x = 10;
void run() {
std::cout << x << std::endl;
std::cout << "pointer to class A" << std::endl;
}
};
int main() {
A *ptr_a = new A();
ptr_a->run();
delete (ptr_a);
ptr_a->run();
}
Output:
10
pointer to class A
-1664078719
pointer to class A
I was expecting a segmentation fault, but it somehow gives me an output where the integer x is some random value(maybe due to memory release) but the string output is still the same.
I think that the pointer sits in the stack pointing to the heap allocated memory where the string is allocated. After deleting the pointer, it releases the memory so that someone else can access it but is still pointing to it and thus the string output is same. But in that sense, what happened to the integer x?
Can someone please explain this in detail as what is happening behind the hood?
Vshi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
4