Search code examples
c++structuredelete-operator

delete structures in c++


Suppose a structure defined as below is allocated dynamically in an array. Would the type, label and description need to null terminated in order to safely delete the allocated structures?

struct operation_data
{
    int number;             
    char* type;             
    char* label;                
    char* description;
}

operation *data=new operation_data[5];  
for (int i=0; i<5; i++)
{
    data[i].type=new char[250];
    data[i].label=new char[250];
    data[i].description=new char[250];
}    
for (int i=0; i<5; i++)
{
    if (data[i].type) delete[] data[i].type;
    if (data[i].label) delete[] data[i].label;
    if (data[i].description) delete[] data[i].description;    
}

My code represents the snippet above. this is causing a Heap corruption detected error in the second delete statement. Please help me rectify this.


Solution

  • no, they dont need to be null terminated. null termination is only an indicator where the string inside the char array ends.

    i would recommend to add a ctor and dtor to your struct to safely delete it.

    struct operation {
      int number;
      char* type;
      char* label;
      char* description;
    
      operation() : type(0), label(0), description(0) {}
      ~operation() {
        if( type )
              delete[] type;
        if( label )
          delete[] label;
        if( description )
          delete[] description;
      }
    };