c - 为什么这个特定的代码会抛出异常?

标签 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,所以它不能太大。

附加信息 有一次甚至堆都“坏了”。

感谢您的帮助。

最佳答案

这个:

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 澄清后)使用“ headless ”链表

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

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

关于c - 为什么这个特定的代码会抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53794568/

相关文章:

C - 如何将文件的第二列存储在数组中?

c++ - 指针的有序关联容器

unit-testing - JUnit 用于具有 Void 返回值的函数

java - 我想从文本文件添加值并将其添加到二维java中。但给出空指针异常

java - 为什么 IOException 不起作用但转到 InputMismatchException

c - c中默认输入空格

c - 影响其他程序的堆溢出

c++ - const char * 数组中的元素数

c++ - 我可以在 C 和 C++ 中可靠地将函数指针设置为 NULL 吗?

c - 这些关于指针的陈述是否具有相同的效果?