0

I for trim string "char array in c and c++ or char pointer" use this function:

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) = '\0';
                return end+1;
        }
    }
    return str;
}

but return this error (reason in code *(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.

please help me.

evergreen
  • 7,771
  • 2
  • 17
  • 25
  • My crystal ball says you called it with a string literal. You can't modify those. A complete example would help greatly. – Retired Ninja Mar 21 '15 at 11:02

1 Answers1

1

No doubt you tried to call this function on a string literal, which is write protected. Make sure you don't use any string literals and you will be fine.

Bad:

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

Good:

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

Also by the way, your function doesn't trim anything if the string is all spaces. I'm not sure if you wanted it that way, but it seems like it should set *str = '\0'; in that case.

JS1
  • 4,745
  • 1
  • 14
  • 19