繁体   English   中英

没有“ 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
Segmentation fault

但是如果我添加const char * test =“”; 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 && ./3
20

我的错误在哪里?

问题在这里:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM