c - 释放内存时出现分段错误错误
问题描述
我试图为列表制作一个自制程序。所以,我创建了一些基本的东西,比如创建列表、添加新节点、显示它们以及删除列表中的所有现有节点。
但是,当我在列表中放入超过 27 个元素时,它会在释放内存时引发分段错误错误。顺便说一句,当我添加 26 个或更少的数量时,效果很好。也许堆栈溢出或类似的东西,我真的不知道。
PS不要告诉我我在开发自行车,这样,先自己做点东西,我更了解事情:)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct node{
struct node * next;
int value;
} node;
int addNode(int position,int value, node ** head,int * size){
int i = 2;
node * curNode = *head;
if(position > *size) return;
while(i <= *size){
if(position == 1){
node * adress = *head;
*head = (node*) malloc(sizeof(node*));
(*head)->next = adress;
(*head)->value = value;
break;
}
else if(i == position){
node * adress = curNode->next;
curNode->next = (node*) malloc(sizeof(node*));
curNode = curNode->next;
curNode->next = adress;
curNode->value = value;
break;
}
else{
curNode = curNode->next;
++i;
}
}
++(*size);
return;
}
void showList(node * head, int size){
int i; node * currentNode = head;
for(i = 0; i < size; ++i){
printf(" %d , next adress: %p |\n", currentNode->value, currentNode->next);
currentNode = currentNode->next;
}
printf("\n");
}
void cleanList(node * head, int size){
int i;
node * curNode = head; node * nextToDelete = NULL;
for(i = 0; i < size; ++i){
nextToDelete = curNode->next;
free(curNode);
curNode = nextToDelete;
}
}
int main() {
node * head = (node*) malloc(sizeof(node*)); //saving head adress to know where the list starts
head->value = 1; //set head value as "1"
int i, size;
node * currentNode = head; //pointer which points to a current node
for(i = 0; i < 5; ++i){
node * adress = (node*) malloc(sizeof(node*)); //variable which saves new node`s adress
currentNode->next = adress; //set this new nod`s adress to previous node`s "next" parametr
currentNode = adress; //set new node`s adress to a current node
currentNode->value = i+2; ///set value for this node
}
size = 6;
addNode(2, 15, &head, &size);
showList(head, size);
showList(head, size);
cleanList(head, size);
return 0;
}
解决方案
您分配的内存不正确。
注意这些行:
*head = (node*) malloc(sizeof(node*));
和
curNode->next = (node*) malloc(sizeof(node*));
您正在为指针分配内存,struct node
而不是实际的结构。
注意这个sizeof
函数——你给它传递了错误的参数!
您的结构包含一个int
和一个指针。这些通常是相同的大小。
但是您只为指针分配内存,因此,您分配了一半的结构。
这将导致您free
在某些时候调用无效地址。您的程序仅在free
运行期间崩溃是一个奇迹,它应该更快地崩溃。
推荐阅读
- pulumi - 检索 VPC 以创建安全组
- unity3d - 使用 RayCastAll 代替 RayCast
- python - 如何在 jupyter 事件小部件上输入和输出参数(单击按钮)
- reporting-services - 为什么我的参数显示错误无法评估 DataSet 的 FilterValues?
- mongodb - Grails MongoDB 插件:v:2 索引键模式中的值不能是 bool 类型
- docker - 将 Dockerfile 指定为管道作业容器
- python - Python tkinter 按钮在 -while 循环条件下不起作用
- python - 使用lmfit python将模型函数参数定义为自变量的函数
- google-cloud-platform - 将数据从变量插入 BQ 表时动态处理 Bigquery 表模式
- oracle - 在 sqlplus 中假脱机时截断行和列