2011-12-24 90 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; 
}