Thursday, May 5, 2022

[SOLVED] Same expression as the destination warning when using snprintf

Issue

(I've seen questions 19202368, 40095973 and href="https://stackoverflow.com/q/1775403/1831722">1775403)

I have this:

char data[32];
memset(data, '\0', sizeof(data));
snprintf(data, sizeof(data), "%s - %d", aCharArray != NULL ? aCharArray : "", anInt);

which yields this warning when compiling on some compilers/architectures: warning: argument to 'sizeof' in 'int snprintf(char*, size_t, const char*, ...)' call is the same expression as the destination; did you mean to provide an explicit length? [-Wsizeof-pointer-memaccess]

Both aCharArray and anInt may be local to the function or passed as arguments. This is a generic example and this is the generic approach I use (using memset to initialize and preferring snprintf to sprintf). I know that if data is local I can use the same size I used to declare it but I prefer to only specify the size in the declaration, once; this way it's easier to change in the future.

Also, snprintf will avoid overflows and put the \0 at the end. strlen will work for a char* passed as argument to the function but it'll be pointless on a freshly initialized or empty (i.e. "") char[].

So, I'm not providing the string length as it may be 0, but I do want to provide the array's size.

Is this approach correct or am I missing some caveat?

On a side note, what's the compiler flag to identify switched parameters? I.e., using the above:

snprintf(data, sizeof(data), "%s - %d", anInt, aCharArray);

Solution

I think it is warning you that data (as used in first param) is the same as data in the sizeof, and that data could be a pointer, not an array (depending on scope).

When it's an array you will get sizeof(char) * count of elements, but if it's a pointer, you will get sizeof(char *).

This is a common source of bugs, partly because it is common to see expressions like sizeof(buffer) / sizeof(buffer[0]) to get the maximum number of elements in an array. It will compile whether buffer is char buffer[n] or char *buffer, but the result is different.

Check your compiler docs to see how to suppress specific warnings if you are satisfied, although you can probably restructure the code also (make the array size a #define for example).

I don't understand identify switched parameters in your side note, you need to put the params in the same order as they are in the format string.



Answered By - Dave Meehan
Answer Checked By - Candace Johnson (WPSolving Volunteer)