为什么此特定代码会抛出异常?

时间:2018-12-15 15:23:44

标签: c pointers exception linked-list nullptr

检测到严重错误c0000374

#pragma once

typedef struct node
{
int value;
node* next;
node* before;
}   node;

void print_nodes(node* list) {
node *current = (node*)malloc(sizeof(node));
//current->value = 0;
current->next = list;

while (current->next != nullptr) {
    printf("%i\n", current->next->value); <-THROW an Exception in the Fist loop
    current->next = current->next->next;
}
free(current);
}

void add_node(node* list) {

}

inline void new_nodes(node* list, size_t anzahl) {
list[0].before = NULL;
for (int i = 0; i <= anzahl; i++) {
    list[i].value = i + 1;
    list[i].next = &list[i + 1];
    list[i + 1].next = &list[i - 1];
}
list[anzahl].next = NULL;
}

printf语句引发一个异常...但仅在某些时候。 我的cpp用size_t = 10调用了函数new_nodes,所以它不能太大。

附加信息一次,甚至是堆“中断”。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

此:

void print_nodes(node* list) 
{
    node *current = (node*)malloc(sizeof(node));
    //current->value = 0;
    current->next = list;

    while (current->next != nullptr) 
    {
        printf("%i\n", current->next->value); <-THROW an Exception in the Fist loop
        current->next = current->next->next;
    }
    free(current);
}

需要大量修改:建议:

修改(在OP明确说明之后)以使用“无头”链接列表

void print_nodes(node* list) 
{ 
    node * current = list; 

    while (current) 
    { 
        printf("%i\n", current->value); 
        current = current->next; 
    } 
}