簡體   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