Search code examples
c++visual-c++buffersizeofbuffering

Buffer size: N*sizeof(type) or sizeof(var)? C++


I am just starting with cpp and I've been following different examples to learn from them, and I see that buffer size is set in different ways, for example:

char buffer[255];
StringCchPrintf(buffer, sizeof(buffer), TEXT("%s"), X);

VS

char buffer[255];
StringCchPrintf(buffer, 255*sizeof(char), TEXT("%s"), X);

Which one is the correct way to use it?

I've seen this in other functions like InternetReadFile, ZeroMemory and MultiByteToWideChar.


Solution

  • Neither is correct.

    You are using StringCchPrintf(), which operates on the count of characters, not bytes. sizeof(buffer) returns the size of buffer in bytes, as does 255*sizeof(char). 255*sizeof(char) also has the disadvantage that you are duplicating the size of the array in two places - if you change the size of buffer but forget in the call to StringCchPrintf, you have a bug.

    This happens to work since sizeof(char) is always 1.

    You are also specifying buffer as char, but use TEXT() around the string - compiling with UNICODE will cause a break.

    Any of the following would be correct:

    char buffer[255];
    StringCchPrintf(buffer, ARRAYSIZE(buffer), "%s", X);
    
    TCHAR buffer[255];
    StringCchPrintf(buffer, ARRAYSIZE(buffer), TEXT("%s"), X);
    
    char buffer[255];
    StringCbPrintf(buffer, sizeof(buffer), "%s", X);
    
    TCHAR buffer[255];
    StringCbPrintf(buffer, sizeof(buffer), TEXT("%s"), X);