C++ intToRoman函数栈缓冲区溢出:触发_fastfail错误求助
Fixing Stack Buffer Overrun in
intToRoman Function Hey there, let's break down what's causing that stack buffer overrun error in your intToRoman function and fix it step by step.
Root Cause of the Error
The error message "Stack cookie instrumentation code detected a stack-based buffer overrun" tells us your code is writing past the bounds of the romanArray char array. Here's exactly why that's happening:
- Insufficient array size: You declared
char romanArray[10];, but the longest valid Roman numeral (for 3999, which isMMMCMXCIX) needs 11 characters plus a null terminator (\0) to be a valid C-style string. That's 12 total slots—your 10-slot array is way too small. - Broken loop logic: Your nested
forloops don't properly decrement values likeM,D,C, etc. For example, the first loop runs 10 times regardless of how manyMs you need, and since you never decreaseM, it will keep writing 'M' to the array until it runs out of bounds. - Incorrect Roman numeral rules: Your code ignores subtractive combinations (like
IVfor 4,IXfor 9,XLfor 40), which not only produces wrong numerals but also miscalculates thecountervalue (subtractive pairs use 2 characters instead of 4 or 9 individual ones).
Step-by-Step Fixes
Let's rewrite the function to eliminate the stack overflow and correctly generate Roman numerals:
- Use
std::stringinstead of a fixed char array: This avoids manual buffer size management entirely—strings grow automatically as needed. - Implement proper Roman numeral rules: Use a list of value-symbol pairs (including subtractive combinations) to build the numeral correctly.
- Remove the flawed
countervariable: We don't need it anymore since we'll iterate through value-symbol pairs directly.
Corrected Code
#include <string> #include <iostream> using namespace std; string intToRoman(int integer) { // Ordered list of value-symbol pairs (includes subtractive cases) const int values[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; const string symbols[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; string roman; cout << "Integer: " << integer << endl; for (int i = 0; i < 13; ++i) { // Append the symbol as long as the value fits into the remaining integer while (integer >= values[i]) { roman += symbols[i]; integer -= values[i]; } } return roman; }
Explanation of the Fixed Code
- Value-symbol pairs: By including subtractive values like 900 (
CM) and 40 (XL), we handle all valid Roman numeral cases without messy conditional logic. - Automatic string resizing: Using
std::stringmeans we never have to worry about buffer overflows—the string grows as we add symbols. - Simplified logic: We iterate through each pair, appending the symbol to the string as long as the current integer is larger than the pair's value, then subtract that value from the integer. This avoids the broken loops from your original code.
内容的提问来源于stack exchange,提问作者Bailey0314
相关产品推荐
相关产品推荐

