C-使用字符串的基于堆栈的缓冲区过度异常


char removeSpaces(char* str)
{
    if (str == NULL)
        return '';
    int i = 0, j = 0;
    while (str[i] != '')
    {
        while (str[i] == ' ')
            i++;
        str[j++] = str[i++];
    }
    str[j] = '';
    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.

我调试了测试案例,并显示:

vstest.executionEngine.x86.exe中的0x627b1b69(spec.dll(的未经处理的异常:堆栈cookie仪器仪器代码检测到了基于堆栈的缓冲区覆盖。

如果有此例外的处理程序,则可以安全地继续该程序。

任何人都可以解释一下。

在跳过空间时,内部循环可以击中'',在i++(在分配中(之后,外循环将不会再看到它,并且将继续扫描> ''之后。如果字符串包含尾随空间,这将发生。


您可以通过使用for((循环来避免将您的 loop逻辑集中在一行上:


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;
}

最新更新