Which implementation of this code is safe?

Char and Charw are my typedefs of the irrlicht types "irr::core::wchar_t" and "c8(char)"

1
2
3
4
Charw* temp2 = Char2Charw((Char*)text.c_str());
.
.
delete[] temp2;

I know text.c_str automatically cleans its own assignment, but i am wondering if when i recast it to (char*) if it creates a new instance that must be freed,

eg do i need this instead, or would this free the managed pointer?:

1
2
3
4
5
6
7
Char* temp= (Char*)text.c_str();
Charw* temp2 = Char2Charw(temp);
.
.
.
delete(temp);
delete(temp2);


PS: here is the func Char2Charw:
1
2
3
4
5
6
7
8
    Charw* Char2Charw(Char*st)
    {
        // Convert to a wchar_t*
        size_t alloc_len = strlen(st) + 1;
        Charw* wc_out = new Charw[alloc_len];
        mbstowcs(wc_out, st, alloc_len);
        return wc_out;
    }
Last edited on
What is the type of text? Is it string? If so, c_str() does not allocate memory and you should not attempt to free/delete it.
Its a string correct. I know that the pointer returned from c_str is managed, but i was worried that if i cast it,
eg:
Char* temp= (Char*)text.c_str();

does this re-cast create a new instance, and should i delete temp afterwards?
does this re-cast create a new instance
No.

should i delete temp afterwards?
No.
Topic archived. No new replies allowed.