c语言fclose的作用,文件读写完后fclose()就内存溢出,该怎么处理

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

linux环境下编译的

#include 

#include 

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;

}

分享到:

更多

------解决方案--------------------

内存越界所致,你看申请的内存:

AccountRecord a = (AccountRecord)malloc(sizeof(AccountRecord));

AccountRecord是指针,sizeof(AccountRecord)申请的大小只有4字节,你却用申请了4字节的指针a去操作整个结构(超过了4字节)。

应该申请整个结构大小的内存才对:

AccountRecord a = (AccountRecord)malloc(sizeof(AccountInfo));

应该就不会有问题了。

------解决方案--------------------

你的这个做法和一个成语有异曲同工之妙:刻舟求剑。

你的struct里的那些指针相当于舟上刻的标记,剑在哪里需要思考。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值