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

前端 未结 7 1648
清歌不尽
清歌不尽 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 21:57

    When using more strict compiler settings, this code shouldn't even compile:

    char* str = "Constant string";
    

    because it should be constant:

    const char* str = "Now correct";
    const char str[] = "Also correct";
    

    This allows you to catch these errors faster. Or you can just use a character array:

    char str[] = "You can write to me, but don't try to write something longer!";
    

    To be perfectly safe, just use std::string. You're using C++ after all, and raw string manipulation is extremely error-prone.

提交回复
热议问题