title: Using 'new' to allocate memory dynamically in C++?
body: <p>I am working on some C++ code and am having some problems with the function described below. I haven't used much C++ before, at least not for a long time and so i'm trying to learn as I go along to a large extent. The win32api doesn't help much with the confusion factor either...</p>
  
  <p>The function is succesfully called twice, before failing when called at a later stage when it is called in the application.</p>
  
  <pre><code>PTSTR getDomainFromDN(PTSTR dnPtstr) {
  
  size_t nDn=wcslen(dnPtstr);
  size_t *pnNumCharConverted = new size_t;
  
  wchar_t *szTemp = new wchar_t[10];          // for debugging purposes
  _itow_s((int)nDn,szTemp,10,10);             // for debugging purposes
  
  AddToMessageLog(EVENTLOG_ERROR_TYPE,szTemp);        // for debugging purposes (displays an integer value before failing)
  AddToMessageLog(EVENTLOG_ERROR_TYPE,TEXT("Marker A"));  // for debugging purposes
  char *dn = new char[nDn];
      // !!!!!!!!!!!! all goes wrong here, doesn't get to next line, nDn does have a value when it fails (61)
  AddToMessageLog(EVENTLOG_ERROR_TYPE,TEXT("Marker B"));  // for debugging purposes
  
  wcstombs_s(pnNumCharConverted,dn,nDn+1,dnPtstr,nDn+1);
  
  ...more code here...
  
  delete[] dn;
  delete pnNumCharConverted;
  
  return result
  }
  </code></pre>
  
  <p>At first i thought it was a memory allocation problem or something as it fails on the line <code>char *dn = new char[nDn];</code>, the last marker showing as 'Marker A'. I used <code>delete[]</code> on the pointer further down to no avail. I know that <code>nDn</code> is a value because I print this out to a message log using <code>_itow_s</code> for debugging. I also know that <code>dnPtrstr</code> is a PTSTR.</p>
  
  <p>I tried using <code>malloc</code> as well with <code>free()</code> in the old C style but this doesn't improve things.</p>