Akra Akra - 2 months ago 9x
C++ Question

Can a new[] *char be delete[](ed)?

I went through previous similar posts and am aware of the fact that in order to simply delete a

I have to use
However, assuming I'm not allowed to use
to put "UNKNOWN" into *data in first place (or make any use of the string library), is there any way to free the memory used by
in this code?

#include <iostream>
#include <stdlib.h>
using namespace std;

class mstring {
char *data;
int length;

length = 8;
data = new char[length];
data = "UNKNOWN";
cout << "In mstring default ctor" << endl;

delete[] data;
cout << "In mstring dtor" << endl;

int main() {
mstring a;
cout << a.data;

The code crashes when trying to delete as "UNKNOWN" can't be deleted.


Your problem lies within the following code:

data = new char[length];
data = "UNKNOWN";

First, you create a new char-array, in the next statement, you loose the only anchor point to it, by overriding it with the address of the literal string "UNKNOWN", which is stored inside of the executable.

When you end up in your destructor, you are trying to delete the memory of your executable, as you no longer refer to the allocated memory.

As you can't use std::string or strcpy, I guess you have to write it yourself:

auto fixedUnknownString = "UNKNOWN";
assert(fixedUnknownString[length] == '\0'); // Lucky coinsidence, extra code required if we wouldn't have an exact match
for (std::size_t i = 0; i < length; ++i) {
    data[i] = fixedUnknownString[i];