Search code examples
c++delete-operator

Issue with deleting a pointer (what it points to)


How to delete the pointer that I assign in the below code:

char* ptr;
ptr=new char(65);   // memory for one char is created and is assigned 'A'
strcpy(ptr,"asdf"); // how can string of length 4 chars are copied
delete ptr;         // why am I getting debug error of Heap corruption detected

I am using Visual C++ 2005


Solution

  • Because you corrupted the heap by trying to stuff 4 characters "asdf" (actually 5 if count null terminator) into a memory block that is only capable of 1 character by doing this:

    strcpy(ptr,"asdf");
    

    Update:

    You should allocate as much memory as needed (or more). If you need to copy a 4-character string into a memory block you should make sure that that the memory block will be large enough to keep it, so, in your case, you should use

    ptr=new char[5];
    

    to allocate 5 chars (4 chars of the string + 1 null terminator every string should have at its end), and to release the allocated memory, you should use

    delete[] ptr;
    

    [] means that you want to delete an array of chars, not just one char.