I've got a question regarding the sizeof() operator. Browsing Open Source projects written in C obviously, some developers tend to use the sizeof() operator in one place and on other places the literal array size.
For example, there is code written like this:
...
char buf[2048];
memset(buf, 0, sizeof(buf));
... = snprintf(buf, 2048, ...);
...
The developer used sizeof(buf) for memset() but referenced the literal buffer size 2048 directly to snprintf() instead of sticking to sizeof(buf). Is this only a bad habit/inconsistency in writing code or was/is the use of sizeof() inappropriate for functions such as snprintf()?
I see this often and really wondered, why not always use sizeof() in such cases? Wouldn't this ease the maintenance of code? Imagine the snprintf() call was somewhere placed much more lower within the function body, a developer changes the size of the buffer on top of the function to e.g. 1024, memset() would catch the change but snprintf() could cause a overflow.
sizeof()in such cases?" -- it's impossible to answer for "such cases" in general, because context matters. It's unclear to what extent the pattern you have presented is representative of any particular code or codebase, or whether some variation that you would lump into that category indeed does have a reason for being written as it is.sizeof, notsizeof(). There's absolutely no need for the parens you've used here.