How to free memory for a structure variable

typdef struct _structname { int x; string y; } structure_name; structure_name variable; 

Now I get access to variable.x and y . After using it, how can I free or free the memory used by variable ?

Actually the memory gets allocated when I do variable.y = "sample string" . Therefore, the = operator allocates memory that causes the problem. how can i solve it now?

+4
source share
5 answers

Memory should be freed only with dynamic allocation.

Dynamic allocation is done using new or malloc , and release is done using delete or free respectively.

If your program does not use new or malloc anywhere, you do not need to use delete or malloc . Note that there will be as many delete as new . The same is true for malloc and free .

That is, in the program:

  • The number of executed new statements is equal to the number of executed delete !
  • The number of malloc statements executed is equal to the number of free !

If the number of executed delete or free less, then your program is a memory leak. If the number of new or malloc executed is less, then your program is likely to crash!

+5
source

You have allocated the structure on the stack. Used memory will be freed when it goes beyond. If you want to control when memory is freed, you should examine the allocation of dynamic memory.

+7
source

In C ++, you do not need to β€œtypedef” your structures.

Using:

 struct structure_name { int x; int y; }; 

If you create myVar this way:

 structure_name myVar; 

You do not need to release it, it will be automatically destroyed and released when you exit the scope.

If you used pointers (created using the "new" keyword), you will need to explicitly release them using the "delete" keyword.

In C ++, you will only use pointers in certain cases.

+3
source

You can control the lifetime of a variable by entering a pair of curly braces { } .

 { structure_name variable; // memory for struct allocated on stack variable.y = "sample string"; // y allocates storage on heap // ... } // variable goes out of scope here, freeing memory on stack and heap 
+1
source

There is no need to free, because you declared them as values, not pointers and do not allocate memory dynamically.

memory should be freed only with dynamic memory allocation.

0
source

Source: https://habr.com/ru/post/1342960/


All Articles