簡體   English   中英

調用free()時出現分段錯誤

[英]Segmentation Fault when calling free()

我正在構建一些模塊化功能,但我不明白為什么釋放模塊后會出現分段錯誤。

我的.h文件

void StringInit(String *this, char const *s)
{
    this->str = strdup(s);
    printf("%s\n", this->str);
}

void StringDestroy(String *this)
{
    if(this == NULL || this->str == NULL)
        return;
    this->str = NULL;
    free(this);
}

int main()
{
    char          *str;
    String        test;

    str = "hello\n";
    StringInit(&test, str);
    StringDestroy(&test);
    return(0);
}

您必須為此this->str調用免費,而不是this (因為您使用strdup分配了一個新字符串)。 此外,將成員設置為NULL不會釋放它:

if (this == NULL || this->str == NULL)
    return;

free(this->str);
this->str = NULL;

代碼中的其他所有內容均按預期工作,您可以在堆棧上分配對象(請記住,您不需要釋放它們)。

free應該用於釋放已經使用malloc分配的指針。 您的test字符串已分配在堆棧上 正如Alfe指出的:

String*  test = (String*)malloc(sizeof(String));
StringInit(test, str);
StringDestroy(test);

正如Adriano的答案所指出的那樣,您還使用strdup分配了一個新字符串。 似乎這里有很多問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM