Reputation: 51
will a re-new of a TCHAR* array has negative/undefined effect? Or even maybe not recommended? Below code has been working fine so far. Need inputs. Thanks!
//e.g.
TCHAR *tc1 = new TCHAR[1];
// later:
//resize TCHARs
tc1 = new TCHAR[size1];
tc1[size1] = { L'\0' };
Upvotes: 1
Views: 1673
Reputation: 27538
The negative effect of the "re-newing" is that you lose the pointer to the free-store memory originally allocated. It will remain occupied throughout the rest of your program, without any chance to reclaim it.
Of course, you may have some other pointer pointing to the memory, but that would be a very strange and unnecessarily complex piece of code.
Avoid all those problems by using std::vector
instead of new[]
.
tc1 = new TCHAR[size1]; tc1[size1] = { L'\0' };
In addition to the memory leak, this is undefined behaviour because size1
is one past the last valid index.
Here's a std::vector
example:
std::vector<TCHAR> tc1(1);
// later:
//resize TCHARs
tc1.resize(size1);
tc1[size1 - 1] = L'\0';
Perhaps even std::string
or std::wstring
is sufficient for your needs.
Upvotes: 2
Reputation: 77334
This is a memory leak. You need to delete
anything created by a new
call. If you do that, everything is fine:
//e.g.
TCHAR *tc1 = new TCHAR[1];
// later:
//resize TCHARs
delete [] tc1;
tc1 = new TCHAR[size1];
tc1[size1] = { L'\0' };
Although on an unrelated note, your last line is writing behind the array you allocated. That's not fine. But it has nothing to do with your allocation of memory, it's a mistake on it's own.
A lot of this can be avoided if you use a string class. Either std::string
or if you are using the MFC, CString
.
Upvotes: 2