无"const char*"分段错误

Segmentation fault without "const char*"

本文关键字:分段 错误 char const      更新时间:2023-10-16

我有一些问题。我尝试此代码并收到"分段错误"错误:

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