【问题标题】:Heap corruption occurs when clearing my linked list清除我的链表时发生堆损坏
【发布时间】:2021-06-20 18:39:18
【问题描述】:

下面的代码可以正常工作。它可以清除列表。

typedef struct Node {
    int data;
    struct Node* node;
}node;

typedef struct List {
    node* head;
    int length;
}list;

int main() {
    list* L = (list*)malloc(sizeof(list));
    L->head = NULL;
    L->length = 0;
    node* p;

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

    head->data = 1;
    head->node = NULL;

    L->head = head;

    while (L->head != NULL) {
        p = L->head;
        L->head = L->head->node;
        free(p);        
    }
}

但是下面的代码在'free(p)'函数中出现错误。

void insert(list* L, int x) {
    node* newnode = (node*)malloc(sizeof(newnode));
    newnode->data = x;

    if (L->head == NULL) {
        newnode->node = NULL;
        L->head = newnode;
    }
    else {
        newnode->node = L->head;
        L->head = newnode;
    }
}

int main() {
    list* L = (list*)malloc(sizeof(list));
    L->head = NULL;
    L->length = 0;
    node* p;

    insert(L, 10);

    while (L->head != NULL) {
        p = L->head;
        L->head = L->head->node;
        free(p);        
    }
}

我查找了有关 HEAP CORRUPTION 错误的信息,发现在尝试释放超出范围的内存时会发生这种情况。但是,两个代码之间的唯一区别是在插入时是否使用函数。那么,为什么会发生这样的事情呢?

【问题讨论】:

    标签: c data-structures linked-list


    【解决方案1】:

    此行不正确:

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

    注意sizeof(newnode)指针 的字节大小,因为这就是newnode。因为struct node 必须大于指针,所以在初始化其成员时会有未定义的行为。本质上,您正在写入不属于您的内存。

    您实际上想要sizeof(node)sizeof(*newnode),因为您正在尝试分配节点结构:

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

    请注意上面我已经删除了转换,因为转换malloc 的返回值是 C 中的反模式。转换的唯一原因是如果您使用的是 C++ 编译器,但如果是这样,那么您应该有将您的问题标记为 C++ 并使用new 而不是malloc

    【讨论】:

      猜你喜欢
      • 2013-06-04
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 2013-04-20
      • 2011-07-18
      • 2019-07-25
      • 2013-01-23
      • 2011-05-12
      相关资源
      最近更新 更多