SPB
SPB

Reputation: 4218

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 causing issue. how can i resolve it now?

Upvotes: 5

Views: 8724

Answers (5)

Nikko
Nikko

Reputation: 4252

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.

Upvotes: 4

aaz
aaz

Reputation: 5196

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

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361622

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 executed delete statements!
  • Number of executed malloc statements is equal to the number of executed free 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!

Upvotes: 5

Vijay
Vijay

Reputation: 67291

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.

Upvotes: 0

Paul Mitchell
Paul Mitchell

Reputation: 3281

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.

Upvotes: 7

Related Questions