【问题标题】:Why Does this particular code throw an exeption?为什么此特定代码会引发异常?
【发布时间】:2018-12-15 15:23:44
【问题描述】:

检测到严重错误 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,所以它不能太大。

附加信息一次,甚至堆“损坏”。

感谢您的帮助。

【问题讨论】:

  • 附加信息一次,甚至堆“坏了”
  • 这个current-&gt;next = current-&gt;next-&gt;next; 太危险了,因为如果current-&gt;next-&gt;next 是NULL 并且下次在while() 循环条件下你要检查NULL-&gt;next,它会导致崩溃。另外我不明白你为什么在 print_nodes() 函数中做 malloc ? add_nodes() 已经创建了列表,print_nodes() 只需打印它。
  • print_nodes() malloc 仅适用于当前它只为一个实例分配内存
  • "太危险了,因为如果 current->next->next 为 NULL 并且下一次在 while() 循环条件中你要检查 NULL->next" 你有什么建议跨度>
  • 异常,投射malloc,nullptr,“cpp”的结果......你确定C标签吗?也许将其更改为 C++ 标记?

标签: c pointers exception linked-list nullptr


【解决方案1】:

这个:

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

【讨论】:

  • Good Suggestion 修改为void print_nodes(node* list) { while (list-&gt;next != NULL) { printf("%i\n", list-&gt;value); list = list-&gt;next; } }
  • 我不太确定这是否会引起一些麻烦
  • 这将是你的“代码”“实现”和“工作”void print_nodes(node* list) { node * current = list; while (current-&gt;next != NULL) { printf("%i\n", current-&gt;value); current = current-&gt;next; } }
  • @TimWeissenfels,您建议的代码假定列表没有“头”指针。我假设会有一个“头”指针,它只包含指向列表中第一个条目的指针
  • @TimWeissenfels,实际上我的代码版本会在正确的时间停止。但是,由于您没有实现“头”指针,它会跳过第一个条目。我将编辑代码以使用您建议的版本。
猜你喜欢
  • 2020-10-01
  • 2020-03-25
  • 1970-01-01
  • 2014-01-10
  • 1970-01-01
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 2014-01-09
相关资源
最近更新 更多