[Solved] Deleting allocated memory pointed by vector element crashes the program [closed]


buffer is allocated with new[], so it must be freed using delete[] instead of delete.

indicator is allocated with new, so it must be freed using delete and not delete[].

And there is no need to check for null, delete and delete[] already handle that for you:

void FreeColumns()
{
    for (auto &column : columns)
    {
        delete[] column.buffer;
        delete column.indicator;
    }
}

That being said, you should use std::vector and std::unique_ptr, then you can get rid of FreeColumns() altogether and simply call columns.clear() when needed.

struct OracleColumnStruct {
    std::string name;
    ub2 ociType;
    FieldType fieldType;
    std::vector<char> buffer;
    std::unique_ptr<sb2> indicator;
    OCIDefine *defineHandler;
};

void AllocateColumns 
{
    columnCount = ... // whatever from database

    for (unsigned int i = 0; i < columnCount; i++)
    {
        ...
        OracleColumnStruct data;
        data.name = "whatever";
        data.ociType = ociType;
        data.buffer.resize(size);
        data.indicator.reset(new sb2);
        // or: data.indicator = std::make_unique<sb2>();

        columns.push_back(data);
       ...
    }
}

2

solved Deleting allocated memory pointed by vector element crashes the program [closed]