c++ new/delete and char *

前端 未结 8 908
醉梦人生
醉梦人生 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:00

    Your initial string s is only five characters long so can't be null terminated. "hello" will be copied by strcpy including the null-terminator but you'll have overrun the buffer. The strlen needs it to be null terminated so if the null's not there, you'll have problems. Try changing this line:

    char *s = new char [6];

    Better still, prefer std::string to C style string functions - they're just as efficient and a lot safer and easier to use. Also, try to avoid new and delete unless you really have to use them. The problems you're getting are very common and can easily be avoided.

提交回复
热议问题