使用字符串的基于堆栈的缓冲区溢出异常

Stack-Based Buffer Overrun Exception using strings

char removeSpaces(char* str)
{
    if (str == NULL)
        return '[=10=]';

    int i = 0, j = 0;

    while (str[i] != '[=10=]')
    {
        while (str[i] == ' ')
            i++;
        str[j++] = str[i++];
    }
    str[j] = '[=10=]';
    return str[0];
}

我在编译器中执行代码没有任何问题。当我在 visual studio 中尝试 运行 它时,我遇到了问题。

测试用例以绿色勾号通过,但之后中止,显示的消息为:

The active Test Run was aborted because the execution process exited unexpectedly. To investigate further, enable local crash dumps either at the machine level or for process vstest.executionengine.x86.exe.

我调试了测试用例,它显示:

Unhandled exception at 0x627B1B69 (spec.dll) in vstest.executionengine.x86.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.

如果有这个异常的处理程序,程序可以安全地继续。

谁能解释一下。

跳过space时,内循环可以命中'[=11=]',而在i++之后(在赋值中),外循环就看不到了,并将在 '[=11=]' 之后继续扫描。如果字符串包含尾随 space.

,就会发生这种情况

您可以通过使用 for() 循环将 循环逻辑 集中在一行中来避免此类簿记错误:


void squeezespace(char*string)
{
size_t i,j;

for(i=j=0; string[i]; i++) { // loop logic on one line
        if( string[i] == ' ') continue;
        string[j++] = string[i] ;
        }
string[j] = 0;
}