开发者

Error in the comp.lang.c FAQ? Calculating the length of a variadically formatted string

Question 15.4: varargs/varargs1.html

In the example code there, they seem to think ‍‍‍va_arg returns NULL if the end of the list has been reached:

len = strlen(first);

va_start(argp, first);

while((p = va_arg(argp, char *)) != NULL)
    len += strlen(p);

va_end(argp);

But the documentation for va_arg explicitly says this is not the case, and that va_arg will happily go past the end 开发者_StackOverflow中文版of the list.

This agrees with my experience trying to imitate the above code and getting a segfault as a result.


Indeed, va_arg doesn't mention returning NULL at the nd of the list.

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

But the FAQ says:

A call to vstrcat looks something like

char *str = vstrcat("Hello, ", "world!", (char *)NULL);

Which means they assume the caller will pass NULL as the last argument to signal the end of the list.


They're passing a NULL pointer in the call to vstrcat().

A call to vstrcat looks something like

    char *str = vstrcat("Hello, ", "world!", (char *)NULL);


Note how vstrcat, in the c-faq article, is called:

char *str = vstrcat("Hello, ", "world!", (char *)NULL);

The last parameter is NULL. That's what va_arg returns

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜