c程序调用结构体崩溃!

struct contact
{
char *name;
char *tel;
};
int static o;
struct contact *stu=(struct contact* )malloc(sizeof(struct contact));

void read()
{
FILE *fp;
int i,m=0;
if((fp=fopen("Communicationrecord.txt","r+"))==NULL)
{
printf("\nCannot open file strike any key return!");
getchar();
exit(1);
}
fseek(fp,0L,0);
while(!feof(fp))
{
fscanf(fp,"%d %s %s ",&o,&stu[m].name,&stu[m].tel);
m++;
}
fclose(fp);
}

main()
{
char *m=(char* )malloc(sizeof(char));
int i;
read();
for(i=0;i<o;i++)
{
strcpy(m,stu[i].name);
printf("\n%s",m);
}
}
哪位大神帮看一下,为啥在strcpy(m,stu[i].name);这个地方会崩溃,讲讲原理,谢谢。

注意了下面的语句:

while(!feof(fp))
{
  fscanf(fp,"%d %s %s ",&o,&stu[m].name,&stu[m].tel); //这里会出问题的。
  m++;
}

你有好几处错误:

    1.你想用结构体数组存放读取的记录,但你分配时错了

struct contact *stu=(struct contact* )malloc(sizeof(struct contact)* 100); //100只是我的假想,你自己的足够大就行

    2.上面的内存分配只是创建了100个结构体,也就是为每个结构体分配了内存空间,而每个结构体的内容就两个指针(32位平台上就8个字节),所以 

 fscanf(fp,"%d %s %s ",&o,&stu[m].name,&stu[m].tel);

就会出错,想想看,你用fscanf的时候数据存储在哪里呢?

你没有给结构体内部的变量分配内存空间。所以,你的

   fscanf(fp,"%d %s %s ",&o,&stu[m].name,&stu[m].tel); 语句前应该加上:

   stu[m].name = (char* )malloc(sizeof(char) * 32); //自己定义合适大小 

   stu[m].tel= (char* )malloc(sizeof(char) * 32); //自己定义合适大小 

    3.主函数中strcpy(m,stu[i].name);也有类似的问题

你先改过来,有问题你再问

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-11-13
m 只给分配了一个字符的空间,而stu[i].name是一串字符。
第2个回答  2014-11-13
char *m=(char* )malloc(sizeof(char));

你之开辟了大小是1个字节
sizeof(char)==>1;
空间大小不够
char *m=(char* )malloc(sizeof(char)*100);
开辟空间不要忘了回收free()
相似回答