Memory access violation. What's wrong with this seemingly simple program?

前端 未结 7 1575
清歌不尽
清歌不尽 2021-01-20 21:50

This is a quick program I just wrote up to see if I even remembered how to start a c++ program from scratch. It\'s just reversing a string (in place), and looks generally c

7条回答
  •  佛祖请我去吃肉
    2021-01-20 22:03

    If you change this, which makes someString a pointer to a read-only string literal:

    char *someString = "Hi there, I'm bad at this.";
    

    to this, which makes someString a modifiable array of char, initialized from a string literal:

    char someString[] = "Hi there, I'm bad at this.";
    

    You should have better results.

    While the type of someString in the original code (char*) allows modification to the chars that it points to, because it was actually pointing at a string literal (which are not permitted to be modified) attempting to do any modification through the pointer resulted in what is technically known as undefined behaviour, which in your case was a memory access violation.

提交回复
热议问题