c++ new/delete and char *

前端 未结 8 929
醉梦人生
醉梦人生 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 11:56

    From man strcpy(3):

    The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest.

    So you need to reserve 6 bytes 5 for the string and 1 for the NULL byte

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

提交回复
热议问题