0
int main () {
    char *str = new char[3];

    //delete[] str; // OK
    delete str;  // OK too

    return 0;
}

I know I need to call delete[] for new []. However, this "delete str" passes compilation. Is there memory leaking in "delete str" in this case?

user1443721
  • 1,110
  • 2
  • 14
  • 33

3 Answers3

0

Yes there is a sure shot memory leak in case of plain delete.

Matching combination must always be:-

new;    
delete;

new[];
delete[];
ravi
  • 10,994
  • 1
  • 18
  • 36
0

Memory allocated with new[] should be deleted with delete[] - otherwise you leak memory. i.e.

int main () {
    char *str = new char[3];
    delete[] str;  // OK
    char *str2 = new char;
    delete str2;  // OK
    char *str3 = new char[3];
    delete str3;  // Not OK
    char *str4 = new char;
    delete[] str4;  // Not OK
    return 0;
}
Constantin
  • 8,721
  • 13
  • 75
  • 126
0

For this example there may not be much difference on most of the systems but it is UB. Deleting buffers using delete which were allocated with new invokes UB.

But if char is replaced with some class, delete[] is guaranteed to call destructors of all objects, while delete may call destructor of obj[0] only which may cause resource leak or some other unwanted issue.

Conclusion: This is UB, so never do this.

Live code here

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • 1
    Understand. If char is replaced with some class, "delete str" cannot pass compilation. However, there is no compilation error for char[3]. That is the reason I ask this question. – user1443721 Nov 07 '14 at 05:19
  • @user1443721 Compilation would be successful. For UB, you may get some warnings possibly if compiler pleases. UB may run smoothly at run time or give run time error or may crash or do something unexpected. – Mohit Jain Nov 07 '14 at 05:21
  • Your answer is acceptable, but I expect compilers CAN treat this the same as other classes. Do you know what is the root cause to make it UB? – user1443721 Nov 07 '14 at 05:32
  • There are few things which are not logical. Such computer code whose behavior is specified to be arbitrary (crash or OK or fail or low performance or burn down the computer), all such possiblities are collectively called UB. Now whether you get or not get compile time warning, run time errors, crash etc, C++ compiler remains compliant because specs don't stops language from invoking those behaviors. Behavior may different for different types, different in different compilers or even different in different version of same compilers. Programmers can not complain, should just avoid invoking UB. – Mohit Jain Nov 07 '14 at 05:35