列表附加功能中的错误
error in list appened function
我在Visual Studio和G 中都遇到了错误,我尝试了GDB,但没有从中获得任何有用的东西
Visual Studio = in array2.exe中的0x00cd464f intherped exception。
gdb给出=程序接收到信号sigsegv,分割故障。列表中的370x000000010040118f :: append(this = 0x23aa80,x = 6)在main.cpp:61
#include <iostream>
#include <stdlib.h>
// "arraylist.h"
#include <new>
//#include "myList.h"
using namespace std;
struct node{
int data;
node* next;
};
struct list{
node* head;
void append(int x);
};
int main()
{
list L;
L.append(6);
node* cur = L.head;
while (cur->next != 0)
{
std::cout << cur->data << std::endl;
cur = cur->next;
}
return 0;
}
void list::append(int x)
{
node* tmp = new node;
node* cur = head;
tmp->data = x;
tmp->next;
if (cur->data == 0)
{
head = tmp;
}
else{
while (cur->next != 0)
{
cur = cur->next;
}
cur->next = tmp;
}
}
一些提示:
-
您不初始化
L.head
(谢谢@Alan Stokes)。 -
您不是初始化
tmp->next
。 -
cur->data == 0
不是检查列表是否为空的正确方法。
您的代码无效,因为当创建列表的对象
时,列表的数据成员头未初始化。struct list{
node* head;
void append(int x);
};
int main()
{
list L; // <== head is not initialized.
您可以写作
list L = { 0 };
或
struct list{
node* head = 0;
void append(int x);
};
in
if (cur->data == 0)
{
head = tmp;
}
您正在尝试访问新创建的list
对象的头部,这意味着您正在使用非初始化的指针。这意味着,每当您解除它时,您都将访问内存的一个不确定的部分,在这种情况下,您不应该访问一部分(这会导致访问违规错误)。我建议在结构构造函数中使用NULL
设置head
,并在尝试访问它的每种方法中检查头是否为NULL
(在这种情况下为list::append(int)
)。
list::list(){
head = NULL;
}
当您使用list L;
相关文章:
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在气泡排序程序中未声明错误功能
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- C++中"覆盖功能的异常规范比基本版本更宽松"的奇怪错误
- 错误:在尝试检测 std::cout 是否<< t 时,功能强制转换为数组类型;有效
- 访问我以前可以访问的功能时出现分段错误
- 分割错误:向量中的擦除功能
- 如何组织 git 工作流以修复错误并同时引入新功能
- 错误:当我尝试使用引用时,使用已删除的功能
- 错误:调用'strcmp'没有匹配函数(尝试设置显示用户信息功能)
- 这种错误的原因是什么:将"功能"重新定义为不同类型的符号
- Boost进程"系统"功能中的错误处理
- 为什么我的删除功能总是出现分段错误
- 想要构建一些必要的库来检测功能.出现一些错误
- C++ 添加编译器警告,以错误使用自定义打印/日志功能
- Visual C:命名空间范围错误或晦涩功能?
- C++插入排序错误功能不起作用
- 错误功能出现问题
- 使用VideoWriter_GPU时如何解决OpenCV错误"功能未实现(当前构建或平台禁用了称为功能)?