关于malloc分配内存冲突的问题

来源:百度知道 编辑:UC知道 时间:2024/06/08 13:49:58
主函数调用了一个包含malloc的子函数,而且malloc在一个while语句里面,调用该子函数第一次的时候能够正常循环,但是第二次调用的时候,再输入数据的时候总是会出现某段内存不能为"writed"的提示。怎么办?
该子函数如下:
struct allt *getaltime(struct allt * hea,struct allt *cur)
{
char ch;
struct allt * pre = NULL;
printf("按任意键继续(退出输入请按'#'):\n");
ch = getch();
while(ch != '#')
{
cur = (struct allt *)malloc(sizeof(struct allt));
if(hea == NULL)
hea = cur;
else
pre->next = cur;
cur->next = NULL;
printf("请输入第%d位选手的 preparation 时间:\n",n+1);
cur->preparation = getnum();
cur->num = n+1;
n++;
pre = cur;
printf("按任意键继续(退出输入请按'#'):\n");
ch = getch();
}
return hea;
}

你的sizeof里面写错了

pFather->pNext=(struct NodeVertex *)malloc(sizeof(struct NodeVertex *));

要改成:

pFather->pNext=(struct NodeVertex *)malloc(sizeof(struct NodeVertex));

其他一样.

因为你要申请一个struct NodeVertex所占的内存,而不是它的指针,一个指针,无论是什么类型,都只是一个地址,大小都是4个字节

看半天 么看明白写的太深懊了