Reputation:
I know that each time i use malloc or calloc i have also to free that memory, but in this specific case i can't understand when free the memory and how, if i free inside the generate()
function the code doesn't work anymore.
void generate(int n){
node *tmp,*new;
int num,i;
head = malloc(sizeof(node));
if (head==NULL){
perror("malloc");
EXIT_FAILURE;
}
num = rand() % (42 - (-42) + 1) - 42;
head->data = num;
head->next = NULL;
tmp = head;
for(i=1;i<n;i++){
new = malloc(sizeof(node));
if(new == NULL){
perror("malloc");
EXIT_FAILURE;
}
num = rand() % (42 - (-42) + 1) - 42;
new->data = num;
new->next = NULL;
tmp->next = new;
tmp = tmp->next;
}
}
int main(){
int n;
do {
printf("give me the size of the linked list (less than 42):");
scanf("%d",&n);
if(n>42){
printf("i said less than 42. \n Please ");
}
} while(n>41);
srand(time(NULL));
generate(n);
printlist();
return 0;
}
Upvotes: 1
Views: 187
Reputation: 375
Use separate function for linked list deletion as follows:
void deleteList()
{
node *tmp = head;
while(tmp != NULL)
{
tmp = tmp -> next;
free(head);
head = tmp;
}
head = tmp;
}
use above function to free memory allocated for linked list
generate(n);
printlist();
// FREE MEMORY
// function call
deleteList();
return 0;
Upvotes: 1
Reputation: 1921
If you free inside your generate() function, by the time your program gets to the printlist() function the memory would be freed (hence your program would not work).
You could free your memory after printlist()...
generate(n);
printlist();
/*
FREE MEMORY
*/
return 0;
But there would be no point, since when your program ends with return 0, the memory is automatically freed by your operating system.
However, if you were to add more code after printlist(), you should still free your memory.
Upvotes: 1