c - C中的链接列表和释放内存
问题描述
我试图制作一个简单的链接列表结构,但由于某种原因,当我测试释放 LL 中的数据时,它会给我一个无效的指针错误。谁能解释为什么?
#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";
你的任务temp
是罪魁祸首,因为它指向静态字符串“Meh\0”,它不是你的free
。在这种情况下,您的 malloc 无效,因为您立即将其替换为指向静态数据。如果要将数据复制到由malloc
.