stack around the variable...was corrupted

Assuming 32-bit int, printing one with %d will yield a maximum of 8 visible characters.

Your format-string also contains 6 literal a-characters, and we should not forget the 0-terminator.

All in all: 2*8+6+1 = 23 > 20 !!

Your buffer must be at least 23 byte big, unless there are other undisclosed input-restrictions.

Personally, I would give it a round 32.

Also, better use snprintf and optionally verify the full string did actually fit (if it does not fit you get a shortened string, so no catastrophe).

char myChar [32];
snprintf(myChar, sizeof myChar, "aa%03daa%daa", i1, i2);

Beware that the Microsoft implementation is non-conforming and does not guarantee 0-termination.


Why did you declare you character buffer a size of 20? More than likely the sprintf placed more characters than that can fit in myChar.

Instead, use

  1. safer constructs such as std::ostringstream or
  2. at the very least, declare you char arrays much bigger than you would expect (not the best way, but would at least not have had the error occur).

If you're going along the "guess the biggest size for my array" route, the last thing you want to do is attempt to count, right down to the last character, how big to make the buffer. If you're off by a single byte, that can cause a crash.

Tags:

C++

Printf

Stack