Question

I am new to c++ and object oriented programming in general. My objective is to use a void pointer to point to an fstream object. I have a structure which contains a void pointer. I want to use the pointer to reference a fstream object so that i can use it in other functions to write into a file using protocol buffer APIs (SerializeToCodedStream).I want to be able to write into the same file through repeated function calls (and read from it). By the way I'm using protocol buffers to serialize data and write into the file.

My structure is:

    typedef struct Store
    {
      void *Obj;  
    } st;

My code to create the fstream object and use the pointer to point to the object

    st *entry1;
    fstream output;
    output.open("file1.txt", ios::out | ios::trunc | ios::binary);
    entry1->Obj=&output;

This is where i'm using the pointer

     int addToFile( st *entry)
     {
     OstreamOutputStream *_OstreamOutputStream;
     CodedOutputStream *_CodedOutputStream;

 _OstreamOutputStream = new OstreamOutputStream(entry->Obj);
     _CodedOutputStream = new CodedOutputStream(_OstreamOutputStream);

      file.SerializeToCodedStream(_CodedOutputStream); //file is an object of a protocol buffer class
      delete _OstreamOutputStream; //this line seems to be causing a segmentation fault when i run the program
      delete _CodedOutputStream;
      }

EDIT: here are the function prototypes for OstreamOutputStream and CodedOutputStream

    OstreamOutputStream (ostream *stream, int block_size=-1);
    CodedOutputStream (OstreamOutputStream *output);

The code compiles without errors but I do get a segmentation fault when I run the program. There is nothing being written into the file either. Any answers on what I'm doing wrong or suggestions of alternate methods would be much appreciated. Thank You.

Was it helpful?

Solution

You are deleting the OstreamOutputStream while it is still being used by the CodedOutputStream. You have to delete the objects in the reverse of the order they were created, so that no object is deleted while some other object is still using it.

I suspect that you also have a second problem: you are creating the fstream as a local variable, which means it will be destroyed as soon as the function returns, making your pointer invalid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top