James Kuyper
5/16/2011 11:28:00 AM
On 05/16/2011 06:52 AM, janus wrote:
....
> On Monday, May 16, 2011 11:26:30 AM UTC+1, Heinrich Wolf wrote:
>> "Ian Collins" <ian-...@hotmail.com> schrieb im Newsbeitrag
>> news:93bdoaFlpiU2@mid.individual.net...
>>> On 05/15/11 06:29 AM, Heinrich Wolf wrote:
>>>>
>>>> or with a macro:
>>>>
>>>> #define STRNCAT(a, b) strncat(a, b, sizeof(a) - strlen(a) - 1)
>>>> char string[10] = "NEW";
>>>> STRNCAT(string, "Jersey");
>>>
>>> That macro would go horribly (and silently) wrong if
>>>
>>> a) 'a' wasn't a fixed sized array, or
>>> b) it was, but the definition wasn't visible when the macro was expanded.
>>>
>>> --
>>> Ian Collins
>>
>> You must not use the macro STRNCAT in e.g. this case:
>>
>> void a_procedure(char *a)
>> {
>> STRNCAT(a, "Jersey");
>> }
>>
>> int main(void)
>> {
>>
>> char string[10] = "NEW";
>> a_procedure(string);
>> }
>>
>> Here sizeof(a) is the size of a pointer and not the size of string. Instead
>> you could do it without the macro:
>>
>> void a_procedure(char *a, size_t size)
>> {
>> strncat(a, "Jersey", size - strlen(a) - 1);
>> }
>>
>> int main(void)
>> {
>>
>> char string[10] = "NEW";
>> a_procedure(string, sizeof(string));
>> }
>
> I do not see any difference between the two
> Janus
In the first version of a_procedure, STRNCAT(a, "Jersey") expands to
strncat(a, "Jersey", sizeof(a) - strlen(a) - 1)
In that expression, sizeof(a) gives the size of the variable 'a', which
is a pointer to char. Therefore, sizeof(a) will be equal to
sizeof(char*). There's a pretty good chance that this will be either 4
or 8, depending upon what platform you're compiling for. It's unlikely
to be 10, though that's not an impossible value.
In the second version, sizeof(string) gives the size of the variable
"string", which is an array 10 char elements, so it is guaranteed to be
10. It's unlikely that this will be the same as sizeof(a); but even if
it is, that's only a coincidence.
--
James Kuyper