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;
}
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 );
}
}