Reputation: 8610
I have been asked in an Interview
What is a memory leak in structures? How can we rectify that?
Can anyone help me in understanding Memory Leak in structure?
Upvotes: 3
Views: 4569
Reputation: 16617
Please take a look at Dynamic memory allocation in C
The common errors that occurs during dynamic memory allocation/free are as follows [which are explained here]
The improper use of dynamic memory allocation can frequently be a source of bugs.
Most common errors are as follows:
free
leads to buildup of memory that is non-reusable memory, which is no longer used by the program. This wastes memory resources and can lead to allocation failures when these resources are exhausted.malloc
, usage to store data, deallocation using free
. Failures to adhere to this pattern, such as memory usage after a call to free or before a call to malloc
, calling free
twice, etc., usually leads to a crash of the program.The above mentioned is applicable to structures
and also to other constructs of C
.
Hope this helps!
Upvotes: 1
Reputation: 206566
The important point to remember is:
Dynamic memory is always allocated as well as deallocated explicitly.
Anytime you allocate a memory to a pointer by using malloc
and do not explicitly call free
on the same pointer/passing same address to free
it results in a memory leak
In case of structures, whenever you have a pointer member which is allocated dynamic memory using malloc
then it should be explicitly free
d by calling free
failing to do so results in memory leak.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
struct MyStruct
{
char *str;
int i;
};
int main()
{
struct MyStruct *ptr = (struct MyStruct *)malloc(sizeof(*ptr));
ptr->i = 10;
/*str is allocated dynamic memory*/
ptr->str = malloc(10);
strncpy(ptr->str,"Hello",6);
printf("[%d]",ptr->i);
printf("[%s]",ptr->str);
/*Frees memory allocated to structure*/
/*But Oops you didn't free memory allocated to str*/
/*Results in memory leak*/
//free(ptr);
/*Correct order of deallocation*/
/*free member memory*/
free(ptr->str);
/*free structure memory*/
free(ptr);
return 0;
}
Upvotes: 1
Reputation: 33457
I guess the obvious answers would be that a leak in a structure is when a pointer that points to allocated memory resides in the structure and the structure goes out of scope before the memory pointed at by its member is freed. It would be rectified by freeing any memory that is pointed to from inside the structure before freeing (or letting go out of scope) the structure.
Pretty sure that's what the question was asking... :)
Upvotes: 6