2

バイナリ ファイルを読み取ってデータベースに保存しようとしていますが、文字列型をデータベースに保存しようとするとセグメンテーション エラーが発生します。正確には、プッシュ関数内でエラーが発生します。

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に変換する必要があります。string

于 2012-04-20T04:22:56.043 に答える