+9

Why only two objects deleted?

There are 4 objects to be destroyed by deleting pointers at bottom of that main function, but only two are deleted. Also there should be three more objects destroyed at end of scope but it s as if execution was stopped. I dont understand why only two. Please help https://code.sololearn.com/cTP4uekU9Gnr/?ref=app

3/13/2019 1:38:07 AM

ChillPill

7 Answers

New Answer

+4

Usually you have a problem if you are using strings and want to save and load them to and from a binary file because a string doesn't have a defined size. So c++ doesn't actually know how many bits it should read back in. Not sure tho if thats causing the problem here and why it would even work then. Would need to check this in a debugger.

+8

it s as if it tries to delete an already deleted thing

+6

thanks for the help. i think i found a clue. the problem seems to be the string i used for the name. this code has the c++11 string removed and all 7 objects are destroyed. why though, not sure. https://code.sololearn.com/cvq9X0tt37XK/?ref=app

+6

yeah sonic it s a weird behavior i dont fully understand. I think that when I do some read/write in binary, it doesnt like that there is a STL string container in my objects and it messes up the pointers.

+4

Probably because writing a string member to a bin is not correct.. It's a serialization problem. That said, when an object is destroyed, STL members are automatically destroyed too.. And you probably saved the string object data and not the data contained(the text) So when you deleted the first object you also called the destructor of the string of the original object. When the original object is destroyed the string is already destroyed => call destructor of unallocated memory == UB ==> The program crash! Using a char buffer solved the problem. If you want to keep using a string member(or a vector,a map ...) you have to define a write and read method inside your class to serialize the data.

+3

Strange. The number of objects destroyed seems to match the number of calls to new. Maybe a coincidence? delete reader2; //delete [] reader; delete &reader[0]; delete &reader[1]; delete &reader[2]; Even explicitly trying to destroy all 3 objects in the array as above makes no change.

+2

I'll try to solve tomorrow. I must go off. Interesting though