C++ Heap Corruption Problem

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--;)
        return ts;

I don’t think it’s easy to see the corruption, if you are interested write me to post the answer. 😉

6 thoughts on “C++ Heap Corruption Problem”

  1. 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 ? 🙂

  2. 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 :).

    1. 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!

Leave a Comment

Your email address will not be published. Required fields are marked *