1

I'm pretty new to c++. I'm reading the contents of a file into a structure like so:

struct wavObj {
    uint8_t *dataBuffer;        // the data   
    int readFile( const char *filePath );

};

int wavObj::readFile( const char *filePath ) {

    FILE *file = NULL;      // File pointer

    file = fopen( filePath, "rb" );

    dataBuffer = new uint8_t[data_Size];
    fread(dataBuffer, data_Size, 1, file);

    fclose(file);

    return 0;


}

Do i need to use the delete operator somewhere to delete wavObj.dataBuffer? Will this struct get destroyed when the program ends, and will the memory allocation get destroyed as well? If not, can i make a destructor that uses the delete operator?

Rob Allsopp
  • 3,309
  • 5
  • 34
  • 53

2 Answers2

0

You should explicitly declare a destructor to free the memory otherwise it may result in overflow.

When your program ends, the allocated memory will not be marked as free and will not be a part of free momory pool. You need to explicitly delete the allocated memory.

But with that you should follow the RULE OF THREE as well

Saksham
  • 9,037
  • 7
  • 45
  • 73
0

As mentioned in comments, a better approach would be to use std::vector<>.

struct wavObj {
    std::vector<uint8_t> dataBuffer;        // the data   
    int readFile( const char *filePath );
};

int wavObj::readFile( const char *filePath ) {
    //...
    dataBuffer.clear();
    dataBuffer.resize(data_Size);
    fread(&dataBuffer[0], data_Size, 1, file);
    //...
}

This avoids the need to define a destructor, copy constructor, and assignment operator (and also the move variants). This is sometimes referred to as the Rule of Three (or the Rule of Three-or-Four-or-Five):

If you left dataBuffer as a bare pointer that received the dynamic allocation, then you would need to add more code to correctly reap the memory as you ascertained. The one place most programmers will know to do clean up is in the destructor.

struct wavObj {
    uint8_t *dataBuffer;        // the data   
    int readFile( const char *filePath );
    ~wavObj () { delete [] dataBuffer; }
};

But, the Rule of Three would dictate the need to also define the copy constructor to properly duplicate the pointer from the object it is copying, and also define an assignment operator to properly clean up the local copy and properly duplicate the pointer from the right hand side. Failure to do so will likely lead to undefined behavior, caused by dangling pointers. Because of the additional complexity, it is better to avoid the issue altogether if possible.

Community
  • 1
  • 1
jxh
  • 69,070
  • 8
  • 110
  • 193