I have a few questions regarding memory handling in C++.
What's the different with Mystruct *s = new Mystruct
and Mystruct s
? What happens in the memory?
Looking at this code:
struct MyStruct{
int i;
float f;
};
MyStruct *create(){
MyStruct tmp;
tmp.i = 1337;
tmp.j = .5f;
return &tmp;
}
int main(){
MyStruct *s = create();
cout << s->i;
return 0;
}
When is MyStruct tmp
free'd?
Why doesn't MyStruct tmp
get automatically free'd in the end of create()
?
Thank you!
When you use the new
keyword to get a pointer, your struct is allocated on the heap which ensures it will persist for the lifetime of your application (or until it's deleted).
When you don't, the struct is allocated on the stack and will be destroyed when the scope it was allocated in terminates.
My understanding of your example (please don't hesitate to inform me if I'm wrong, anyone):
tmp
will indeed be "freed" (not the best word choice for a stack variable) at the end of the function since it was allocated on the stack and that stack frame has been lost. The pointer/memory address you return does not have any meaning anymore, and if the code works, you basically just got lucky (nothing has overwritten the old data yet).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With