Re: Cutest bug you have ever seen?
Trying to clear something like std::string with memset may or may not work, depending on how it is implemented. It also assumes that the 'cleared' state for the object is to have all of its members set to zero. This is not necessarily the case.
eg.
Both 'pdata' & 'unused' are corrupted by the memset.
Code:
class Data10
{
public:
Data10() : pdata(new int [10]), unused(true)
{
}
~Data10()
{
delete[] pdata;
}
int Get(int i)
{
unused = false;
return pdata[i];
}
void Set(int i, int value)
{
unused = false;
pdata[i] = value;
}
bool Unused()
{
return unused;
}
private:
int *pdata;
bool unused;
};
int main()
{
Data10 data;
memset(&data, 0, sizeof(Data10)); // Error!!!
}
Re: Cutest bug you have ever seen?
Quote:
Originally Posted by Peter_APIIT
I understand what is POD and non POD types. AFAIK, POD types is like int, char and void pointer.
Non POD types are like string or object.
I wonder what worng with that.
See this code and comments.
Code:
foo f; // f is already constructed
memset(&f, 0, sizeof(foo)); // Now you've wiped away the string data that was already constructed!!
What if the string sets members to certain values. By calling memset(), you have literally destroyed the string's data, and it is now in an inconsistent state.
What if the string is reference counted, and the string object has an internal reference count? Let's say the reference count set in the string is 6 (meaning there are currently 6 strings with the same data). Now you go ahead and use memset(), destroying this information. You now have a live string with a wrong reference count. Using the string causes all sorts of bad things to happen.
What if the non-POD member has an internal v-table? By memset()-ing, you've wiped out the v-table. There are so many other scenarios I could mention, and the reason why using memset() in a C++ program can get you in a lot of trouble.
Regards,
Paul McKenzie
Re: Cutest bug you have ever seen?
Thanks for your all explanation.
Re: Cutest bug you have ever seen?
Quote:
and the reason why using memset() in a C++ program can get you in a lot of trouble.
And would probably get you into to trouble in 'C' too for many of the same reasons.