I was trying to make a simple Link List struct but for some reason when I tested freeing up the data in the LL it would give me an invalid pointer error. Can anyone explain why?
#include <stdio.h>
#include <stdlib.h>
void add();
typedef struct node{
char* data;
struct node* next;
} node;
node** n;
int main(int argv, char** argc){
n = (node**)malloc(sizeof(node*)*10);
int i;
for(i = 0; i < 10; i++){
n[i] = NULL;
}
add();
free(n[0]->data);
return 0;
}
void add(){
char* temp = (char*)malloc(sizeof(char)*4);
temp = "Meh\0";
n[0] = (node*)malloc(sizeof(node));
n[0]->data = temp;
}
char* temp = (char*)malloc(sizeof(char)*4);
temp = "Meh\0";
Your assignment to temp
is the culprit, as that sets it to point to the static character string "Meh\0", which it not yours to free
. Your malloc has no effect in this case, as you immediately replace it to point to static data instead. Use memcpy or similar if you want to copy the data into the memory allocated by malloc
.