C语言中加载结构的分段错误

时间:2018-03-23 05:08:24

标签: c++

我正在使用C /的fopen()和putc()函数,并希望实现结构的序列化/反序列化。但是,这里有一些"分段故障"发生错误。我调查了类似的问题,发现当我试图访问一些不属于我的记忆时会发生这种情况。

我应该在代码中修复哪些内容才能使其正常运行?

struct Account {
string holder_name;
string holder_password;
double current_sum;
};

int save_to_file(Account * account);
Account * load_from_file(string holder_name);

int main(){
    Account account = { "BEN", "password", 200.0 }; 
    save_to_file(&account);
    load_from_file("BEN");
    return 0;
}

int save_to_file(Account * account){
    const char * cstr = account->holder_name.c_str();
    int size = sizeof(struct Account);

    FILE * fp = fopen(cstr, "wb");
    char * c;

    c = (char *) account;

   for(int i=0; i < size; i++)
   {
       putc(*c++, fp);
   }   

   return fclose(fp);
}

Account * load_from_file(string holder_name)
{
    FILE * fp;
    char *c;
    int i;
    int size = sizeof(struct Account);
    struct Account * ptr = (struct Account *) malloc(sizeof(struct Account));

    if ((fp = fopen(holder_name.c_str(), "rb")) == NULL)
    {
        perror("Error occured while opening file");
        return NULL;
    }

    c = (char *)ptr;

    while ((i = getc(fp))!=EOF)
    {
        *c = i;
        c++;
    }

    fclose(fp);
    return ptr;
}

1 个答案:

答案 0 :(得分:3)

string类型不属于C语言,它是来自C ++的对象。

由于可以使用对象内部的指针实现,因此您不能简单地将其二进制值写入文件:当您稍后读取文件时,不会分配指向的内存。

一个简单的规则是将指针值写入文件可能是一个错误。

要使代码生效,只需将string类型替换为char []即可。以下是仅进行此修改的代码:

#include <stdlib.h>
#include <stdio.h>

struct Account {
    char holder_name[100];
    char holder_password[100];
    double current_sum;
};

int save_to_file(struct Account * account);
struct Account * load_from_file(char *holder_name);

int main(){
   struct Account account = { "BEN", "password", 200.0 }; 
   save_to_file(&account);
   load_from_file("BEN");
   return 0;
}

int save_to_file(struct Account * account){
   const char * cstr = account->holder_name;
   int size = sizeof(struct Account);

   FILE * fp = fopen(cstr, "wb");
   char * c;

   c = (char *) account;

   for(int i=0; i < size; i++)
   {
       putc(*c++, fp);
   }   

   return fclose(fp);
}

struct Account * load_from_file(char *holder_name)
{
   FILE * fp;
   char *c;
   int i;
   int size = sizeof(struct Account);
   struct Account * ptr = (struct Account *) malloc(sizeof(struct Account));

   if ((fp = fopen(holder_name, "rb")) == NULL)
   {
       perror("Error occured while opening file");
       return NULL;
   }

   c = (char *)ptr;

   while ((i = getc(fp))!=EOF)
   {
       *c = i;
       c++;
   }

   fclose(fp);
   return ptr;
}