I am reading strings in C++ using fread where I am reading and storing shortSiteText in siteNames_. siteNames_ is declared as std::vector<char*> siteNames_; I use siteNames_ in other functions but because shortSiteText is a pointer, when I call the delete command on it, the last entry in siteNames_ is changed. How do I prevent this?
for (unsigned int i = 0; i <= nSites; i ++){
fread((char *) &shortSiteTextLength, 1, sizeof shortSiteTextLength, baseFile_);
shortSiteText = new char[shortSiteTextLength];
fread(shortSiteText,1, shortSiteTextLength,baseFile_);
siteNames_.push_back(shortSiteText);
}
delete [] shortSiteText;
I tried to use the dereference operator: siteNames_.push_back(*shortSiteText); but that generates a compiler error.
NOTE: I must use fread and char* due to legacy code.
Let’s zoom on this:
Explanation: The second line just pushes a pointer to the array, not the array itself. The first line then desallocate the array, on which the last element of siteNames still points to; this leads to undefined behavior when you use this element.
Hack: Remove
delete [] shortSiteTextReal fix: You encounter this problem because you try to manage object ownerships yourself. Don’t ! Here, you can use
std::stringand still be able to work with legacy code, with thec_str()member function.To quote a friend of mine: