Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cstring - debug assertion failed; buffer too small

I have this piece of code which keeps throwing a 'buffer too small' error during debug.

        geoGraph.size=limit;
        CString xAxis ="X axis: ",yAxis="Y axis: ";

        for (int x = 0; x < limit; x++)
        {

            xAxis.Format(_T("%s%i  "),xAxis,(x+1));
            yAxis.Format(_T("%s%s  "),yAxis,dialog_test.str[x]);

        }

        xAxis.Format(_T("%s \n%s  "),xAxis,yAxis);// <---Error thrown

        d.SetWindowTextA(xAxis);

I came into the conclusion that the error was due to the fact that the Cstring xAxis is too small to contain the new text, am I correct and if so, how do I remedy it?


Thanks.

Edit: I'm curios as to why this error is only shown during debugging and not when I'm running the application with 'start without debugging' (I use VS2008).

like image 877
Madz Avatar asked Dec 02 '25 04:12

Madz


1 Answers

No! The real problem was:

  1. xAxis Format starts and sees that there is need for more room. Based on the calculation of all the parameters given to Format.
  2. Now xAxis storage is reallocated. The old pointer gets invalid and in the debug Version frees and overwrites it. So there is no 0 terminator any more. The memory is filled with a standard value for free Memory.
  3. Format starts and collects from the old pointer (The Contents where it Points to just changed) and copies garbage and finds no 0 terminator.

Never use a CString in Format as target AND source! This might work in the Release Version, because the Memory MIGHT not be changed, but if it is changed the behaviour is undefined. But it is a real bad coding bug.

like image 176
xMRi Avatar answered Dec 04 '25 18:12

xMRi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!