how to free memory for structure variable
typdef struct _structname
{
int x;
string y;
} structure_name;
structure_name variable;
Now I access variable.x
and y
. After using it how can i deallocate or free the memory used by variable
?
Actually the memory is getting allocated when i am doing variable.y="sample string".So the = operator allocates memory which is causin开发者_运维知识库g issue. how can i resolve it now?
You've allocated the structure on the stack. The memory it's using will be freed when it goes out of scope. If you want to have control over when the memory is freed theh you should investigate dynamic memory allocation.
Memory needs to be deallocated only when it's dynamically allocated.
Dynamic allocation is done using either new
or malloc
, and deallocation is done using delete
or free
respectively.
If your program doesn't use new
or malloc
anywhere, then you don't need to use delete
or malloc
either. Note there will be as many number of delete
as there are new
. And same is true of malloc
and free
also.
That is, in a program:
- Number of executed
new
statements is equal to the number of executeddelete
statements! - Number of executed
malloc
statements is equal to the number of executedfree
statements!
If there are less number of executed delete
or free
, then your program is Leaking Memory. If there are less number of executed new
or malloc
then your program will most likely crash!
In C++ you don't need to "typedef" your structures.
Use:
struct structure_name
{
int x;
int y;
};
If you create myVar this way:
structure_name myVar;
You don't need to deallocate it, it will automatically be destroyed and freed when going out of scope.
If you had used pointers (created with the "new" keyword ) you'd need to free them explicitly using the "delete" keyword.
In C++ you will use pointers only in specific cases.
The lifetime of a variable can be controlled by introducing a pair of 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
No need to free since you have declared them as values and not pointers and not allocationg memory dynamically.
memory needs to be freed only when you allocate memory dynamically.
精彩评论