无"const char*"分段错误
Segmentation fault without "const char*"
我有一些问题。我尝试此代码并收到"分段错误"错误:
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
struct Stack {
int value;
Stack *next;
};
void push(Stack* top, int value) {
Stack *ntop = new Stack;
ntop->value = top->value;
ntop->next = top->next;
top->next = ntop;
top->value = value;
}
int pop(Stack* top) {
int val = top->value;
top->value = top->next->value;
top->next = top->next->next;
return val;
}
int main()
{
Stack *top;
top->next = NULL;
push(top, 20);
cout << pop(top);
}
[10:40:46] [~]>> g++ 3.cpp -o 3 &&./3分段错误
但是如果我添加常量字符* 测试 = ";在 Stack *top 之前;它工作正常:
int main()
{
const char* test = "";
Stack *top;
top->next = NULL;
push(top, 20);
cout << pop(top);
}
[10:47:33] [~]>> g++ 3.cpp -o 3 && ./320
我的错误在哪里?
问题就在这里:
Stack *top;
top->next = NULL;
您正在引用未初始化的指针。这是未定义的行为。因此,任何事情都可能发生,并且可能与周围的代码不一致。
我想你忘了实际为top
分配一些东西.
int main()
{
Stack *top = new Stack; // Allocate
top->next = NULL;
push(top, 20);
cout << pop(top);
delete top; // Free
return 0;
}
*虽然我想指出,代码中仍然会有内存泄漏。
int main()
{
Stack *top;
top->next = NULL;
如果这是原始 C,你会将一个NULL
写入垃圾位置——top
变量尚未初始化,所以它指向垃圾。->next
将跟随您的垃圾指针,然后以 4 或 8 个字节的偏移量写入它。还是垃圾。
也许C++为你做了一些魔术struct
==class
魔术初始化 - 我不知道C++足以评论 - 但你可能还在看垃圾。
添加test = ""
会适当地更改内存布局,以便覆盖进程地址空间内的某些内容。它仍然是垃圾,所以谁知道你破坏了什么:)但它并没有立即崩溃。
用一些东西初始化你的top
变量:
Stack *top;
top = malloc(sizeof Stack);
if (!top) {
/* die */
}
您尚未为 top
分配任何内存。 分配内存将解决问题(完成后不要忘记释放它(。 添加 const char * 可能只是通过在堆栈上放置另一个变量来掩盖问题(这是非常随机的,并且特定于编译器,这实际上使问题看起来已经解决(。
将Stack *top
更改为 Stack *top = new Stack()
。
#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
struct Stack {
int value;
Stack *next;
};
void push(Stack* top, int value) {
Stack *ntop = new Stack;
ntop->value = top->value;
ntop->next = top->next;
top->next = ntop;
top->value = value;
}
int pop(Stack* top) {
int val = top->value;
top->value = top->next->value;
top->next = top->next->next;
return val;
}
int main()
{
Stack *top = new Stack();
top->next = NULL;
push(top, 20);
cout << pop(top);
return 0;
}
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?