2011-12-24 14 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

あなたは[タグ:c]というタグを付けましたが、[タグ:C++]ヘッダーと 'using namespace std;'で書かれています。 CまたはC++を記述しますか? 1つを選択してそれに固執するのが最善です - 2つは以前よりも互換性がありません。 – sarnold

+0

それは私の大学の運動、私はSTLを好む –

答えて

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

ありがとう、それは動作します。 –

1

topのメモリを割り当てていません。メモリを割り当てると問題が解決されます(完了したら解放することを忘れないでください)。 const char *を追加すると、別の変数をスタックに置くだけで問題が隠されます(実際は問題が解決されているように見えるので、非常にランダムでコンパイラ固有です)。これは、生のCだったら

2
int main() 
{ 
    Stack *top; 
    top->next = NULL; 

、あなたはゴミの場所にNULLを書くことにしたい - top変数が初期化されていないので、ゴミを指します。 ->nextはガベージポインターの後ろに4バイトまたは8バイト離れたオフセットで書き込みます。まだゴミ。

多分C++はいくつかの魔法を持っていますstruct == classあなたのために魔法の初期設定があります - 私はC++についてよくコメントしていませんが、おそらくまだゴミを見ているでしょう。

test = ""を追加すると、プロセスのアドレス空間内にあるものを上書きするだけのメモリレイアウトが変更されます。それはまだゴミだから、あなたが壊したものを誰が知っているのですか?ただちにクラッシュしませんでした。

何かであなたのtop変数の初期化:Stack *top = new Stack()

Stack *top; 
top = malloc(sizeof Stack); 
if (!top) { 
    /* die */ 
} 
1

変更Stack *topを。

#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; 
} 
関連する問題