Double delete of data doesn't crash

前端 未结 3 390
心在旅途
心在旅途 2021-01-19 23:57

I am trying to learn C++ and was writing programs to learn Copy Constructors and Operator overloading. I am surprised that the below program when Copy constructor is used do

3条回答
  •  终归单人心
    2021-01-20 00:40

    Your program has undefined behavior.

    Problems:

    data = new char (strlen(str) + 1 );
    

    This doesn't allocate strlen(str) + 1 characters. Instead, it allocates a single character and places the strlen(str) + 1 value within. When you perform a strcpy afterwards, you are corrupting the stack through buffer overflow (writing strlen(str) -1 chars past the allocated space). To allocate an array you should use square brackets:

    data = new char [strlen(str) + 1 ];
    

    Second, you should delete the data with delete[] data;. Otherwise, you get undefined behavior.

    Third, your strcpy code doesn't copy the NULL terminator of the string. You should add a null terminator:

    data[ strlen(str) ] = 0;
    

    after the strcpy lines; (see comments).

    Additionally, there is no requirement that an application would crash on double delete. Deleting the same memory twice is UB.

提交回复
热议问题