2011-12-24 93 views
1

我有一些问题。 我试试这个代码,并收到 “分段故障” 错误:没有“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 *测试= “”;之前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

在我的错误呢?

+3

您已经标记了[tag:c],但是已经用[tag:C++]标题和'using namespace std;'编写 - 这是什么?你想写C或C++吗?最好选择一个并坚持下去 - 这两个比以前更少互换。 – sarnold 2011-12-24 08:53:33

+0

它只是我的大学锻炼,我更喜欢STL – 2011-12-24 08:58:37

回答

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

*虽然我想指出的是,你仍然有代码中的内存泄漏。

+0

非常感谢你,它的工作原理。 – 2011-12-24 09:00:21

1

您还没有为top分配任何内存。分配内存将解决问题(不要忘记在完成时释放它)。添加const char *可能只是通过在堆栈上放置另一个变量来掩盖问题(这是非常随机的,并且特定于编译器,这实际上使得问题看起来被解决了)。

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

变化Stack *topStack *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; 
}