1

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' }; 
nvoigt
  • 75,013
  • 26
  • 93
  • 142
jude
  • 51
  • 1
  • 9
  • 3
    Such code does not _resize_ the array, it discards the previous pointer to an array (causing a memory leak), and overwrites `tc1` with a pointer to a new array. – Algirdas Preidžius Dec 23 '17 at 11:24
  • If you deallocate the allocated memory then it should not have any negative effect. – Asesh Dec 23 '17 at 11:24
  • 2
    Besides, if you are explicitly using ``L`` prefix for wide characters then I see no reason to use TCHAR, use wchar_t instead or use _T or TEXT macro. Remember, using TCHAR will make your code unportable – Asesh Dec 23 '17 at 11:28

2 Answers2

2

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.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • Might probably want to use `std::basic_string` instead of `std::string` if they use `TCHAR` in the first place. – eerorika Dec 23 '17 at 15:10
2

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.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62