没有“const char *”的分段错误

时间:2011-12-24 08:51:02

标签: c++ pointers stack segmentation-fault

我有一些问题。 我尝试这段代码并收到“Segmentation fault”错误:

#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

但如果我在 Stack * top; 之前添加 const char * test =“”; ,它的工作正常:

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

我的错误?

4 个答案:

答案 0 :(得分:4)

问题在于:

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

*虽然我想要指出代码中仍然存在内存泄漏。

答案 1 :(得分:2)

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 */
}

答案 2 :(得分:1)

您尚未为top分配任何内存。分配内存将解决问题(完成后不要忘记释放它)。添加const char *可能只是通过在堆栈上放置另一个变量来掩盖问题(它是非常随机的和编译器特定的,这实际上使得问题似乎得到解决)。

答案 3 :(得分:1)

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