Programme crashes while deallocating a character array

后端 未结 6 1672
刺人心
刺人心 2021-01-21 14:36

When I run the .exe being created with the below code in debug mode , it shows some assertion failure and the programme crashes But when i run the same exe created from the rele

6条回答
  •  梦谈多话
    2021-01-21 14:50

     char *buf  = new char[5];   //pre-allocated buffer
    

    Here you define a pointer, and initialize it to point to a dynamically allocated buffer with room for 5 characters.

    buf = "Hello";
    

    Here you initialize the pointer to point to the beginning of a string literal.

     delete [] buf;
    

    Here you delete[] the buf pointer, but the buf pointer no longer points to anything you new[]'d up, it points to the string literal. You can only delete/delete[] a pointer that points to something you got from new/new[]. So you get undefined behavior, and likely crash

    You likely meant to copy the content of your string into the buffer you new[]'d. Remember to account for the nul terminator:

    int main()
    {
        char *buf  = new char[6];   //pre-allocated buffer
        strcpy(buf, "Hello");
        delete [] buf;
        getchar();
        //cout<

    Though, in C++, you'd rather use std::string from #include ;

    std::string = "Hello";
    

提交回复
热议问题