簡體   English   中英

釋放內存時出現分段錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM