I was testing how C++ manages memory and their allocation. I’ve stumbled on something I can’t seem to figure out. I’m sure it has a simple explaination, but the rabbithole on memory in general got to me. So I ask your help.
I know that if you have the following code, that the address of property A in B is unvalid because the stack will delete ‘a’ when it leaves the getvar() function.
#include <iostream>
class A{
public:
int prop = 2;
};
class B{
public:
A* prop;
};
void getvar(B&);
int val;
int main()
{
B b;
std::cout << &b <<"n";
getvar(b);
std::cout << b.prop <<"n";
std::cout << &((*b.prop).prop);
}
void getvar(B& b){
A a;
b.prop = &a;
std::cout << &a << "n";
std::cout << &((*b.prop).prop);
}
However, following this logic I tested this code:
#include <iostream>
class Cap{
public:
int param;
};
class Form{
public:
Form() {
Cap cap;
cap.param = 4;
}
void func(){
std::cout << &cap << "n";
}
int s = 5;
Cap cap;
};
int main()
{
Form form;
std::cout << &form << "n";
std::cout << &form.cap << "n";
std::cout << &form.cap.param << "n";
form.func();
std::cout << form.cap.param << "n";
}
I assumed that, when the constructor of form is called, a new instance of cap is created. However, as soon as the program leaves the constructor, following the previous logic, I assumed the cap variable would be addressing released stack memory, and thus be invalid.
Now, the tests I made showed me that the cap property is alive and kicking but why?
And what if the cap property was a pointer (e.g. Cap* cap;
) would it cause problems?
Thanks in advance!