In my application's InitInstance function, I have the following code to rewrite the location of the CHM Help Documentation:
CString strHelp = GetProgramPath();
strHelp += _T("MeetSchedAssist.CHM");
free((void*)m_pszHelpFilePath);
m_pszHelpFilePath = _tcsdup(strHelp);
It is all functional but it gives me a code analysis warning:
C26408 Avoid
malloc()andfree(), prefer thenothrowversion ofnewwithdelete(r.10).
When you look at the official documentation for m_pszHelpFilePath it does state:
If you assign a value to
m_pszHelpFilePath, it must be dynamically allocated on the heap. TheCWinAppdestructor callsfree( )with this pointer. You many want to use the_tcsdup( )run-time library function to do the allocating. Also, free the memory associated with the current pointer before assigning a new value.
Is it possible to rewrite this code to avoid the code analysis warning, or must I add a __pragma?
Technically, you can take advantage of the fact that
new/deletemap to usualmalloc/freeby default in Visual C++, and just go ahead and replace. The portability won't suffer much as MFC is not portable anyway. Sure you can useunique_ptr<TCHAR[]>instead of directnew/delete, like this:For robustness for replaced
newoperator, and for least surprise principle, you should keepfree/strdup.If you replace multiple of those
CWinAppstrings, suggest writing a function for them, so that there's a single place withfree/strdupwith suppressed warnings.