Search code examples
c++arraysstringnew-operatordelete-operator

Proper use of delete vs delete[ ] with respect to char * in C++


I have a piece of code:

#include<iostream>

using namespace std;

int main()
{
    char * str = new char;

    cin >> str;
    cout << str;

    delete str;
}

vs.

#include<iostream>

using namespace std;

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

    cin >> str;
    cout << str;

    delete []str;
}

When I give input to either program using STDIN, which program ensures that there are no memory leaks?

This doubt arose as our professor told us that a char * is basically equivalent to an array of chars only. So if I allocate heap memory as in the first case and let str 'hold' an array of chars, if I then delete str, does it delete the array completely? I know that the second case manages to do so.

I have already been through ->

delete vs delete[] operators in C++

delete vs delete[]

And thus I know that delete[] deletes memory allocated by new[] and delete does the same for new. But what if new itself allocates contiguous memory locations??


Solution

  • Your both first code example is wrong.

    char * str = new char;  
    cin >> str;
    

    You've only allocated memory for a single character. If you read anything other than an empty string, you'll write into unallocated memory and will have undefined behaviour.

    if I then delete str, does it delete the array completely?

    It will only delete the one character that you allocated. The rest of the string that you wrote in unallocated memory won't be directly affected by the delete. It's not a memory leak, it's a memory corruption.

    vs.

    char * str = new char[];
    

    This is not legal c++. Array size must be specified.

    EDIT: After your fix, the second code is correct as long as you read a string of 29 characters or shorter. If you read a longer string, you'll get undefined behaviour again.

    But what if new itself allocates contiguous memory locations?

    It doesn't. new (as opposed to new[]) allocates and constructs exactly one object. And delete destroys and deallocates exactly one object.

    TLDR Neither program has memory leaks but the first one has undefined behaviour due to memory corruption.