i am in the process of learning linked lists, and i dont understand the behavior change when freeing a string. Here is the code:
#include <stdio.h>
#include <stdlib.h>
struct node {
char* data;
struct node* next;
};
void Push(struct node** headRef, char *data)
{
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef; // The '*' to dereferences back to the real head
*headRef = newNode; // ditto
}
int main(int argc, const char * argv[])
{
char* auxStr;
struct node* list;
struct node* auxPtr;
int i=5;
while (i<9)
{
auxStr=malloc(sizeof("String:%d"));
sprintf(auxStr, "String:%d",i);
Push(&list, auxStr);
i++;
}
auxPtr=list;
i=0;
while (auxPtr)
{
printf("Node:%d - Data:%s\n",i++,auxPtr->data);
auxPtr=auxPtr->next;
}
return 0;
}
That results in:
Node:0 - Data:String:8 Node:1 - Data:String:7 Node:2 - Data:String:6 Node:3 - Data:String:5
now, when i add free(auxStr) in the first while:
while (i<9)
{
auxStr=malloc(sizeof("String:%d"));
sprintf(auxStr, "String:%d",i);
Push(&list, auxStr);
free(auxStr);
i++;
}
i now get:
Node:0 - Data:String:8
Node:1 - Data:String:8
Node:2 - Data:String:8
Node:3 - Data:String:8
Can someone explain why ? i know it may not be the most efficient code freeing in there multiple times, but i saw this behavio and it is puzzling me. Would appreciate your help to help me understand the concept better.
Thanks