Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory questions, new and free etc. (C++)

I have a few questions regarding memory handling in C++.

  1. What's the different with Mystruct *s = new Mystruct and Mystruct s? What happens in the memory?

  2. 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!

like image 296
shuwo Avatar asked Dec 14 '22 00:12

shuwo


1 Answers

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).

like image 65
Sapph Avatar answered Dec 15 '22 13:12

Sapph