试图读取或写入受保护的内存:内存的 C++ 修改值

Attempted to read or write protected memory : C++ Modified Value of Memory

我为 trim 字符串 "char array in c and c++ or char pointer" 使用这个函数:

inline char * trimRight(char * str)
{
    char * end = str + strlen(str);
    while(str != end)
    {
        end--;
        switch(*end)
        {
            case ' ':
            case '\t':
            case '\n':
            case '\v':
            case '\f':
            case '\r':
            break;
            default:
                *(end+1) = '[=10=]';
                return end+1;
        }
    }
    return str;
}

但是 return 这个错误(代码中的原因 *(end+1) = '\0' ):

An unhandled exception of type 'System.AccessViolationException' occurred in x.exe

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

请帮帮我

毫无疑问,您试图在写保护的字符串文字上调用此函数。确保你不使用任何字符串文字,你会没事的。

差:

char *s = "hello   ";
trimRight(s);

好:

char s[] = "hello   ";
trimRight(s);

另外,如果字符串全是空格,您的函数不会 trim 任何东西。我不确定你是否想要那样,但在那种情况下似乎应该设置 *str = '[=12=]';