2

我正在尝试读取二进制文件并将其存储到数据库中,但是当我尝试将字符串类型存储到数据库中时出现分段错误。准确的说,错误发生在push函数内部:

new_node->name = name;

我似乎无法在网上找到一个好的解决方案,而且我漫无目的地尝试不同的东西......任何帮助将不胜感激。

// 
// loadbin.cpp
//

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

#include "studentsDB.h"

int main( int argc, char* argv[] ) {

    string name;
    string id;
    int numCourses;
    int crn;
    vector<int> crns;

    studentsDB sDB;
    studentsDB::node *students = 0;

    int in = 1;

    if( argc > 1 ) {

        ifstream infile(argv[in], ios::binary );

        while( !infile.eof() ) {
            infile.read( ( char* )(name.c_str()), sizeof( string ) );
            infile.read( ( char* )(id.c_str()), sizeof( string ) );
            infile.read( ( char* ) &numCourses, sizeof( int ) );

            do{
                crns.push_back( crn );
            }
            while( infile.read( ( char* ) &crn, sizeof( int ) ) );

            sDB.push( &students, (string)name, (string)id, numCourses, crns );
        }
        //sDB.printList( students );
    }


    else
        cout << "Not enough argument" << endl;
}


void studentsDB::push( struct node** head_ref, string name, string id,
                       int numCourses, vector<int>crns ) {

    struct node* new_node = ( struct node* ) malloc(sizeof(struct node));
    new_node->name = name;
    //new_node->id   = id;
    new_node->numCourses = numCourses;
    //new_node->crns = crns;
    new_node->next = (*head_ref);    
    (*head_ref)    = new_node;
    size++;
}
4

1 回答 1

3

这段代码很糟糕:

        infile.read( ( char* )(name.c_str()), sizeof( string ) );

您不能写入由 返回的缓冲区c_str(),它不能保证足够长来保存您的结果。 sizeof(string)顺便说一句,与字符串可以容纳的大小无关。您需要分配自己的char[]缓冲区来保存 的结果infile.read,然后转换为 a string

于 2012-04-20T04:22:56.043 回答