Search code examples
c++resizetchar

Re-'new' TCHAR* array


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' }; 

Solution

  • 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.