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
中分配给a
和b
时使用main
系列功能。
另外,malloc(sizeof(Date))
应该是malloc(sizeof(name))
,并且yoy应该在free(x)
的末尾(或main
的末尾)为freeelem
。
关于c - 无结构元素功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36413226/