c++ new/delete and char *

前端 未结 8 891
醉梦人生
醉梦人生 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");
    
    0 讨论(0)
  • 2021-02-02 11:56

    You've corrupted s2 pointer by

    strcpy(s, "hello");
    

    Because s has size 5, while you've missed that strcpy includes string terminator.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-02 12:02

    strcpy includes the null terminator; strlen does not. Write:

    char *s1 = new char [strlen(s) + 1];
    
    0 讨论(0)
  • 2021-02-02 12:11

    You need to specify char *s1 = new char [strlen(s) + 1]; to make room for the '\0' which terminates the string.

    0 讨论(0)
  • 2021-02-02 12:14

    new char [strlen(s)]; does not count the closing \0 character, so your buffer is too short by one character.

    0 讨论(0)
提交回复
热议问题