-1

I have 2 code like this

Code 1: CString::Format method

CString cStr;
char* ToString(CString pszFormat, ...)
{
    va_list argList;
    va_start(argList, pszFormat);
    cStr.FormatV(_T(pszFormat), argList);
    va_end(argList);
    return (LPTSTR)(LPCTSTR)cStr;
    //Note that this will return the pointer to the cstring content
}

Code 2: sprintf_s method

char strChar[100];
char* ToString(char const* const _Format, ...)
{
    va_list argList;
    va_start(argList, _Format);
    vsprintf_s(strChar, _Format, argList);
    va_end(argList);
    return strChar;
    //Note that this will return the pointer to the string content
}

In code 1, I feel totally safe - I don't have to afraid about the length maybe too long. But I'm afraid that code 1 may reduce the performance. I don't know if it may cause memory leak or not. And I think that if Cstring has dynamic length, maybe it will allocate and free memory like no one business.

So I come up with code 2. But in code 2, I face the risk if I pass the _Format too long - like string that has length as 1000 - then the program will crash with 'buffer too small' error.

I don't know which one is better: CString::Format or sprintf_s ??? If sprintf_s really increase performance and CString::Format is bad for performance, then I'll take more effort to prevent 'buffer too small' in sprintf_s. But if sprintf_s not worth it - I'll take CString::Format.

Thank for reading.

123iamking
  • 2,387
  • 4
  • 36
  • 56
  • Both implementations are complete bogus. The first one returns a non-const pointer to immutable object internals. If you feel safe about this, you need to read a few books from [The Definitive C++ Book Guide and List](http://stackoverflow.com/q/388242/1889329). The second one will corrupt memory. Since you are concerned about performance, and don't care about correctness, it is trivially easy to optimize either implementation to take no time at all. Besides, if you cannot measure performance, you shouldn't care anyway. – IInspectable Jan 01 '17 at 13:25
  • @IInspectable Thank you for your advise. – 123iamking Jan 03 '17 at 01:34

1 Answers1

0

If you are worried that the buffer in strChar might overflow, then why not simply use vsnprintf_s(). The second argument will restrict the number of characters written to the output buffer. You can modify your 'ToString()' function to receive this extra sizeOfBuffer field and pass it on to vsnprintf_s().

See [https://msdn.microsoft.com/en-us/library/d3xd30zz.aspx][1] for the details and other ways to prevent a buffer overrun.

Mark S
  • 21
  • 3
  • But my question is about the disadvantage and advantage of CString::Format vs sprintf_s. You totally ignore CString::Format – 123iamking Aug 29 '16 at 15:07