Eric Sosman <> writes:
> On 2/24/2012 8:08 PM, nroberts wrote:
>> Say I do this:
>>
>> void fun(char buffer[2048]) ...
>>
>> and then assume that any buffer I'm passed in will have 2048 bytes.
>>
>> That's silly, right? At least with gcc I can pass in any size array
>> there. Pretty sure I recall C not being able to do this but that was
>> years ago before it started pulling in behavior from C++ where that
>> actually works.
>
> You're right: The declaration as it stands is equivalent to:
>
> void fun(char *buffer)
>
> ... and an array of any size at all, or even a pointer to a free-
> standing `char', or even a null pointer, can be the argument value
> that initializes this parameter.
>
> There is nothing I know of that gives the exact guarantee you
> seem to seek, but there's something that's close:
>
> void fun(char buffer[static 2048])
>
> ... says that the argument is an array of *at least* 2048 elements
> or points to a `char' with *at least* 2047 additional `char's after
> it, but still does not prevent you from passing an array of [4000].
>
> Note that the type of the parameter `buffer' is still `char*',
> so `sizeof buffer' is `sizeof(char*)', which is unlikely to be as
> large as 2048.
Yes, it *says* that the argument is (or rather points to) an array of at
least 2048 elements, but there's nothing to enforce that.
Here's what the C standard says (N1570 6.7.6.3p7):
A declaration of a parameter as "array of _type_" shall be
adjusted to "qualified pointer to _type_", where the type
qualifiers (if any) are those specified within the [ and ] of the
array type derivation. If the keyword static also appears within
the [ and ] of the array type derivation, then for each call to
the function, the value of the corresponding actual argument
shall provide access to the first element of an array with at
least as many elements as specified by the size expression.
Since this is not a constraint, the word "shall" in the last sentence
merely means that the compiler is permitted to generate code that
*assumes* that "buffer" points to a sufficiently large array. If it
doesn't, then the behavior is undefined.
No diagnostic is required for a call such as "fun(NULL)" (and gcc
doesn't issue a warning).
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Will write code for food.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"