In the last six months I am consulting a company in C++. Today my colleague and I find out a very tricky heap corruption. Below is presented a C++ snapshot with the heap corruption. Can you see the problem ?
string Core::ntos(unsigned int n){ string ts= ""; if( !n ) return ts= "0"; char i= 0; string tmpstr= ""; char s; while( n ){ tmpstr[i++] = (char)(n %10 +48); n/= 10; } for(; i--;) ts.push_back(tmpstr[i]); return ts; } }
I don’t think it’s easy to see the corruption, if you are interested write me to post the answer. π
Hi Toni,
Isn’t the problem in the second loop you’re calling ?
If we enter the first loop 3 times, the last populated index of ‘tmpstr’ will be 2. But ‘i’ will be 3.
Later on, in the second loop, you’re calling for with a condition containing ‘i–‘ . Maybe the first iteration of that loop will contain i = 3, not i = 2. Therefore – heap corruption of the array of characters.
Is that the reason ? π
Hi Kosta, as I wrote in the previous comment, the problem is related with index operator which doesn’t check whether the index is out of range!
Tony, if this is a STL string, it should assert in Debug. If not then Ivan suggested to define the _SECURE_SCL macro to 1. This will help you to catch all out of range problems run-time :).
Hi Drago, actually we are working on embedded device in Linux environment, so _SECURE_SCL won’t help us ;-).
You are right the problem is that “operator[]” doesn’t check for index which is out of range!
Tony, this was easy, give us something more challenging π
Ok, I will post a new soon π