文件读写完后fclose()就内存溢出

lonelyandrew 2013-12-29 09:01:57
linux环境下编译的
#include <stdlib.h>
#include <malloc.h>
typedef struct
{
char *CardCode;
char *Name;
char *Contact;
char *Password;
char AccountType;
double MoneyCount;
}*AccountRecord, AccountInfo;

int AccountInfoWrite(AccountInfo Record)
{
FILE *fp;
char *FileName="12345678.Bq";
fp=fopen(FileName, "w");
if (fp==NULL)
{
printf("文件已新建! \n");
return 1;
}
if (fwrite(&Record, sizeof(AccountInfo), 1, fp) == 1)
{
printf("账户信息写入成功! \n");
fclose(fp);
return 0;
}
else
{
printf("账户信息写入失败! \n");
return 1;
}
}

void read()
{
AccountInfo buffer;
FILE *fp;
fp=fopen("12345678.Bq", "rb");
if (fp==NULL)
{
printf("open file error!\n");
return;
}
fread(&buffer, sizeof(AccountInfo), 1, fp);
fclose(fp);
printf("%s \n", buffer.Name);
}

int main()
{
AccountRecord a = (AccountRecord)malloc(sizeof(AccountRecord));
a->Name = "aassasasa";
a->CardCode = "12345678";
a->Contact = "110";
a->Password = "112233";
a->AccountType = 'a';
a->MoneyCount = 111.00;
AccountInfoWrite(*a);
read();
return 0;
}

...全文
160 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
lonelyandrew 2013-12-29
  • 打赏
  • 举报
回复
多谢各位,一遇到指针就头疼啊,还是应该多看看c
神农氏 2013-12-29
  • 打赏
  • 举报
回复
你的这个做法和一个成语有异曲同工之妙:刻舟求剑。 你的struct里的那些指针相当于舟上刻的标记,剑在哪里需要思考。
Mr. Code 2013-12-29
  • 打赏
  • 举报
回复
内存越界所致,你看申请的内存:
AccountRecord a = (AccountRecord)malloc(sizeof(AccountRecord));
AccountRecord是指针,sizeof(AccountRecord)申请的大小只有4字节,你却用申请了4字节的指针a去操作整个结构(超过了4字节)。 应该申请整个结构大小的内存才对:
AccountRecord a = (AccountRecord)malloc(sizeof(AccountInfo));
应该就不会有问题了。

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧