2019-08-23
Why can't we delete an initialized pointer?
stackoverflow
Question

I am initializing a char pointer with some random values, and when I am trying to delete it, I am unable to. Why is that?

Here is what I am doing:

int main()
{
    char *s = new char[50];    /* 
                                * I know there is no reason for 
                                * using new if initializing, but 
                                * in order to use delete we need 
                                * to allocate using new.
                                */
    s = "Harry";
    delete s;
    return 0;
}
Answer
1

If you really want to practice with pointer, you need to fix your code. The main problem is you are trying to assign string literal( which is const char[6] in here) to pointer s then try to modify it by calling delete which invoke undefined behavior(UB).

char *s = new char[50];    
strcpy(s, "Harry");     // don't assign string literal to it
                        // re-assign pointer to string literal,
                        // lost pre-allocated memory position and caused delete to fail 
                        // it's UB to modify string literal
delete []s;             // new[]/delete[], new/delete need to be called in pair. 

Just use std::string instead.

#include <string>
std::string s("Harry"); // no worries
Why can't we delete an initialized pointer?
See more ...