rock-ass rock-ass - 1 year ago 124
C++ Question

C++ Out of scope delete operator of an object causes crash deallocating std::vector

I have a problem, that when I try to delete manually allocated pointer, it causes SIGABRT, I can't get to the roots of the cause. The class looks like

class StreamMetadataReader {

protected:
std::ifstream csvFile;
std::vector<std::string> header;

public:
bool openFile(const std::string& path);
};


The object is created manually allocating memory using
new
operator and stored in a third party library memory:

auto* reader = new StreamMetadataReader;
vxSetNodeAttribute(
node, VX_NODE_ATTRIBUTE_LOCAL_DATA_PTR, (void *) &reader, sizeof(StreamMetadataReader *)
);


And the pointer address is passed around functions during program execution. I can cast the address to object type and use it properly. At the end of the program, I retrieve the pointer for the last time and call delete operator to free the memory like so:

StreamMetadataReader *reader = nullptr;
vxQueryNode(
node, VX_NODE_ATTRIBUTE_LOCAL_DATA_PTR, (void *) &reader, sizeof(StreamMetadataReader *)
);
if (reader != nullptr) {
delete reader;
}


So the debugger says that execution stops when the default destructor tries to free
std::vector<std::string> header;
object member.

Maybe someone has an idea what is wrong here?
I know this is not the best practice solution for this exact problem. Maybe I this could be a use case for some sort of smart pointer (e.g. weak pointer)?

Thanks in advance.

Answer Source

Thanks everyone for your help, I have only recently solved my problem, and that was that I had wrong defines in my project, and that caused my program to be compiled with slightly different headers than the shared library I used. The library I used had precompiler conditions to declare structure members. That caused memory corruption and errors appeared spuriously everywhere.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download