释放内存时出现分段错误错误

时间:2019-11-30 23:23:41

标签: c

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

但是,当我在列表中放入27个以上的元素时,在释放内存时会引发分段错误。顺便说一句,当我添加不超过26个时,效果很好。也许堆栈溢出或类似的东西,我真的不知道。

P.S不要告诉我我正在开发一辆自行车,这样,我自己先做点东西,我会更好地了解:)

#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;
}

1 个答案:

答案 0 :(得分:3)

您分配的内存不正确。

请注意以下几行:

clock

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

您正在为指向curNode->next = (node*) malloc(sizeof(node*)); 的指针分配内存,而不是实际的结构。
注意struct node函数-您为它传递了错误的参数!

您的结构包含一个sizeof和一个指针。通常尺寸相同。
但是,您只为一个指针分配内存,因此,您分配了一半的结构。

这将导致您有时在无效地址上呼叫int。 这是一个奇迹,您的程序仅在free操作期间崩溃了,应该早就崩溃了。