C++ 变量周围的堆栈...已损坏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25223741/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:16:58  来源:igfitidea点击:

stack around the variable...was corrupted

c++stackprintf

提问by student1

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.

我有一个简单的函数,可以将一些数据写入一个新文件。它可以工作,并且文件已写入,但是在 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.

正如所见,我只是使用 sprintf 将一些变量插入到字符串中(工作正常)。现在无论我通过 myChar 还是 new_char,它仍然给我损坏错误。

What went wrong?

什么地方出了错?

采纳答案by PaulMcKenzie

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

为什么你声明你的字符缓冲区大小为 20?很可能sprintf放置的字符多于可以放入 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).
  1. 更安全的结构,例如 std::ostringstream 或
  2. 至少,声明你的 char 数组比你预期的要大得多(不是最好的方法,但至少不会发生错误)。

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.

如果您沿着“猜测我的数组的最大大小”路线前进,那么您要做的最后一件事就是尝试计算缓冲区的大小,一直到最后一个字符。如果你偏离了一个字节,那可能会导致崩溃。

回答by Deduplicator

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

假设 32-bit int,打印一个 with%d将产生最多 8 个可见字符。

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

您的格式字符串还包含 6 个文字字符a,我们不应该忘记 0 终止符。

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

总之:2*8+6+1 = 23 > 20!!

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

除非有其他未公开的输入限制,否则您的缓冲区必须至少为 23 字节大。

Personally, I would give it a round 32.

就个人而言,我会给它一个回合 32。

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

此外,更好地使用snprintf并可选择验证完整的字符串确实适合(如果它不适合,您会得到一个缩短的字符串,所以没有灾难)。

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

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

请注意,Microsoft 实施不符合标准,并且不保证 0 终止。