简体   繁体   English

调用free()时出现分段错误

[英]Segmentation Fault when calling free()

I'm building some modular function and I'm not getting why I get a segmentation fault after freeing my module. 我正在构建一些模块化功能,但我不明白为什么释放模块后会出现分段错误。

My .h file 我的.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);
}

You have to call free for this->str , not for this (because you allocated a new string with strdup ). 您必须为此this->str调用免费,而不是this (因为您使用strdup分配了一个新字符串)。 Moreover set a member to NULL doesn't free it: 此外,将成员设置为NULL不会释放它:

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

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

Everything else in your code works as expected, you can allocate objects on stack (just remember you don't need to free them). 代码中的其他所有内容均按预期工作,您可以在堆栈上分配对象(请记住,您不需要释放它们)。

free should be used to free pointers that have been allocated using malloc . free应该用于释放已经使用malloc分配的指针。 Your test string has been allocated on the stack . 您的test字符串已分配在堆栈上 As Alfe points out: 正如Alfe指出的:

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

And as Adriano's answer points out, you've also allocated a new string with strdup . 正如Adriano的答案所指出的那样,您还使用strdup分配了一个新字符串。 Seems like there are a myriad of issues here! 似乎这里有很多问题!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM