I'm writing a program in C language and I used malloc() in a function. Do I have to use free() after in the function? Will it cause a memory leak if I don't free it since it is just a function?
Thank you.
void insertFirst(int key, int data) {
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
//point it to old first node
link->next = head;
//point first to new first node
head = link;
}
CodePudding user response:
The function adds a node that was dynamically allocated within the function to a singly-linked list.
Within the function you shall not free the allocated memory for the node. Otherwise the list will refer to an invalid object.
You need to write a function that will free all the allocated memory (nodes) for the list when the list is not needed any more.
For example the function can look the following way (taking into account that the pointer head
is declared as a global variable in your implementation of the list)
void clear( void )
{
while ( head != NULL )
{
struct node *tmp = head;
head = head->next;
free( tmp );
}
}
CodePudding user response:
Once your program allocates memory, it remains allocated until your program frees it.
Generally, you are not required to free memory. In general-purpose multi-user operating systems, the operating system releases all resources your program held when the program exits. However, it is generally good practice to release memory when your program is done using it. This is particularly so in programs that do various things repetitively. If, in each repetition, a program allocated memory and did not free it, then the program’s use of memory would grow and grow over time. That can interfere with other programs running on the system.
In simple student programs, you will not observe any bad effects from failing to free a little memory, other than tools that diagnose memory leaks complaining. However, it is a good practice you must learn for writing practical programs later.
Generally, functions that allocate memory are paired with functions that release memory. At the lowest level, malloc
allocates memory and free
releases it. Then, in your function to add a node to a linked list, insertFirst
would allocate memory using malloc
and would not release it, because the memory is needed to hold the object in a linked list. Rather, insertFirst
would be paired with some function that removes a node from the linked list, and that function would call free
to release the memory.