首页 > 解决方案 > 释放内存时出现分段错误错误

问题描述

我试图为列表制作一个自制程序。所以,我创建了一些基本的东西,比如创建列表、添加新节点、显示它们以及删除列表中的所有现有节点。

但是,当我在列表中放入超过 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;
}

标签: c

解决方案


您分配的内存不正确。

注意这些行:

*head = (node*) malloc(sizeof(node*));

curNode->next = (node*) malloc(sizeof(node*));

您正在为指针分配内存,struct node而不是实际的结构。
注意这个sizeof函数——你给它传递了错误的参数!

您的结构包含一个int和一个指针。这些通常是相同的大小。
但是您只为指针分配内存,因此,您分配了一半的结构。

这将导致您free在某些时候调用无效地址。您的程序仅在free运行期间崩溃是一个奇迹,它应该更快地崩溃。


推荐阅读