typedef struct //this is a some structure
{
    char *a,*b;
    float x;
}name;
void freeelem(void *x) //the function for element mem free
{
    free(((name*)x)->a);
    free(((name*)x)->b);
}
void* allocelem() //
{
    void *aux;
    aux=malloc(sizeof(name));
    return aux;
}
int main()
{
    void *x=allocelem();
    ((name*)x)->a="fdasf";
    ((name*)x)->b="fafas";
    freeelem(x);
    return 0;
}


我不明白为什么这会给段错误。是我访问结构的方式吗?
................................................... ....................................

最佳答案

freeelem函数中,对free系列函数未获得的指针调用malloc。这会导致不确定的行为。

要解决此问题,请删除那些free调用;或在malloc中分配给ab时使用main系列功能。

另外,malloc(sizeof(Date))应该是malloc(sizeof(name)),并且yoy应该在free(x)的末尾(或main的末尾)为freeelem

关于c - 无结构元素功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36413226/

10-11 22:11
查看更多