文件读写完后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里的那些指针相当于舟上刻的标记,剑在哪里需要思考。