[英]Segmentation fault error while freeing the memory
我試圖為列表制作一個自制程序。 所以,我創建了一些基本的東西,比如創建列表、添加新節點、顯示它們以及刪除列表中的所有現有節點。
但是,當我在列表中放入超過 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
運行期間崩潰是一個奇跡,它應該早點崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.