Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stack around the variable...was corrupted

Tags:

c++

stack

printf

I have a simple function that writes some data to a new file. It works, and the file is written, but I get the above mentioned error while debugging in MSVS Express 2013.

void writeSpecToFile(const char *fname); //in header file.

char myChar [20];
sprintf(myChar, "aa%03daa%daa", i1, i2);
const char* new_char = myChar;
writeSpecToFile(myChar);

As seen, I simply insert some variables into a string using sprintf (works fine). Now whether I pass myChar or new_char, it still gives me the corruption error.

What went wrong?

like image 579
student1 Avatar asked Aug 09 '14 22:08

student1


2 Answers

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.

like image 173
PaulMcKenzie Avatar answered Oct 22 '22 04:10

PaulMcKenzie


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.

like image 40
Deduplicator Avatar answered Oct 22 '22 03:10

Deduplicator