Evan Carslake
Evan Carslake

Reputation: 2359

C++ delete what wchar_t* points to

Title might be confusing. This is a simple thing, but I have searched and tried for an hour now. I have tried everything I have found.

code:

void test() {


// Convert
wchar_t* wcBuff;
wstring value = convert::stringToWideChar(str);
wcBuff = (wchar_t*)value.c_str();

// Draw Text
g->DrawString(wcBuff,...);

// Clean
delete wcBuff;


}

The delete causes the program to crash.

Upvotes: 0

Views: 4076

Answers (3)

Vincent Damewood
Vincent Damewood

Reputation: 141

Don't explicitly delete wcBuff. It points to memory that belongs to value, and will be deleted when value falls out of scope.

Consider this code:

#include <cstdlib>

class alloc
{
    char* memory;

public:
    alloc() { memory = static_cast<char*>(std::malloc(32)); }
    char* get_buff() { return memory; }
    ~alloc() { std::free(memory); }
};

int main()
{
    alloc x;
    char* y = x.get_buff();

    delete y;
}

In this example, the alloc class uses a mechanism other than new/delete to allocate and deallocate memory (old C functions, in this case). Calling delete y in main causes a crash. Since main is a function, and x is allocated as one of the function's local variables, x.~alloc() will be called when main exits, freeing the memory that x owns.

Upvotes: 3

Sergio
Sergio

Reputation: 143

You must not free the memory yourself, because you didn't allocated it yourself.

The (wchar_t*)value.c_str() statement returns a pointer to memory that is owned by wstring and will be released automatically in its destructor when the function ends (when value goes out of scope).

Upvotes: 2

Matthias Wimmer
Matthias Wimmer

Reputation: 4009

The memory buffer you get from .c_str() is managed by the wstring itself. You should not free it. It gets freed by the destructor of wstring.

As well only pointers allocated with the new operator should/can get freed using the delete operator. As a c string it's probably memory allocated using malloc() which get's freed by free(). But this is an implementation detail of your standard library. Just don't free the memory on your own.

Upvotes: 1

Related Questions