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

前端 未结 7 1551
清歌不尽
清歌不尽 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:18

    You're trying to modify a string literal - a string allocated in static storage. That's undefiend behaviour (usually crashes the program).

    You should allocate memory and copy the string literal there prior to reversing, for example:

    char *someString = "Hi there, I'm bad at this.";
    char* stringCopy = new char[strlen( someString ) + 1];
    strcpy( stringCopy, someString );
    strReverse( stringCopy );
    delete[] stringCopy;//deallocate the copy when no longer needed
    
    0 讨论(0)
提交回复
热议问题