c++ new/delete and char *

前端 未结 8 1000
醉梦人生
醉梦人生 2021-02-02 11:50

Can anyone help me, why I\'m getting an error message while trying to free the allocated memory: Heap corruption detected. CTR detected the application wrote the memory after en

8条回答
  •  轮回少年
    2021-02-02 12:18

    char *s = new char [5];
    strcpy(s, "hello");
    

    Causes Undefined behavior(UB).
    You are writing beyond the bounds of allocated memery. You allocated enough memory for 5 characters but your string has 6 characters including the \0.

    Once your program has caused this UB, all bets are off and any behavior is possible.

    You need:

    char *s = new char [strlen("hello") + 1];
    

    In fact the ideal solution is to use std::string and not char *. These are precisley the mistakes which std::string avoids. And there is no real need of using char * instead of std::string in your example.
    With std::string:

    • You don't need to new anything
    • You don't need to delete anything &
    • You can do everything with std::string, that you do with char *.

提交回复
热议问题