Access violation error when reversing a string c++

2020-05-06 12:03发布

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

The following simple function should reverse a character array in place.

void reverse(char* str)
{
    char* last = str;

    // find end of the string
    while(*last) {
        ++last;
    }

    // swap characters until the pointers meet in the middle
    while(str < last)
    {
        --last; 
        char temp = *str;
        *str = *last;
        *last = temp;
        ++str;
    }
}

int main()
{
    char* a= "Hello";
    reverse(a);
    return 0;
}

The code compiles. But it throws a runtime error about access violation. According to the debugger the culprit is the line below:

char temp = *str;

Any ideas why it happens?

标签: c++ char
1条回答
Luminary・发光体
2楼-- · 2020-05-06 12:57
char* a= "Hello";

The pointer a points to a string literal. According to the standard, attempting to modify a string literal results in undefined behaviour. In the case of your implementation, the segmentation fault indicates that the compiler is choosing to place the string literal in non-modifiable memory.

Declare a to be a string that is modifiable. For example, like this:

char a[] = "Hello";
查看更多
登录 后发表回答