vendredi 31 août 2018

Data read from the file, but a core dumped error occurs

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


class C{
    private:
        int work_loc, floor_no;
    public:
        C(){}
        void printC(){
            std::cout << "work Location: " << work_loc << "  floor_no: " << floor_no;
        }
        C(int work_loc1, int floor_no1): work_loc(work_loc1), floor_no(floor_no1){}
};

class B{
    private:
        int empid_;
        std::string name_;
        C obj_c;
    public:
        B(int empid, std::string name, int work_loc, int floor_no): empid_(empid), name_(name){
            obj_c = C(work_loc, floor_no);
        }
        void printB(){
            std::cout << empid_ << " " << name_ << "\n ";
            obj_c.printC(); 

        }


};

class A{
private:
    std::vector<B> calls;
public:
    void addToCalls(B b){
        calls.push_back(b);
    }
    void printAll(){

        for(size_t i = 0; static_cast<int>(i) < 3; i++){
            std::cout << "i is " << i << "\n";
           calls[i].printB(); 
        }

    }
    int callSize(){
        return calls.size();
    }


};


int main(){
    A a, c;

    a.addToCalls(B(1,"a1", 1, 33));
    a.addToCalls(B(2,"b2", 3 ,44));
    a.addToCalls(B(3,"c2", 4, 55));
    a.addToCalls(B(4,"d3", 5, 22));
    a.addToCalls(B(5,"e4", 3, 88));
    a.printAll();
    std::cout << "end of a\n";  
    // FILE* f;
    // FILE* f1;
    // f = std::fopen("serial.txt", "w+");
    std::cout << "begin another a \n  ";
    std::fstream  f;
    std::fstream  f2;
    f.open("class_data.txt", std::ios::out|std::ios::binary);
    f.write((char*)&a, sizeof(a));

    // fwrite(a, sizeof(a), sizeof(a), f);
    // fwrite(&n, sizeof(int), 1, f);
    f.close();
    // rewind(f);
    // f.open("class_data.txt", std::ios::out | std::ios::binary);
    f2.open("class_data.txt", std::ios::in | std::ios::binary);
    f2.read((char*)&c, sizeof(c));
    std::cout << "the size of C is " << c.callSize() << "\n"; 
    c.printAll();
    // f.close();
    f2.close();


}

Here I get the data gets copied into the object c, but it gives out an error. After the values are printed, the code gives the core dumped error. The value of the object is copied from the file, which is also written at the same time. Is it because of the 2 file pointers opening the same file? Here's the backtrace

Aborted (core dumped)

======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fae6020e7e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fae6021737a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fae6021b53c]
./a.out[0x4028ea]
./a.out[0x40276a]
./a.out[0x402564]
./a.out[0x4021e3]
./a.out[0x401c80]
./a.out[0x401ad6]
./a.out[0x401635]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fae601b7830]
./a.out[0x4010c9]

Aucun commentaire:

Enregistrer un commentaire