Nulls in variadic C functions

我怕爱的太早我们不能终老 提交于 2019-12-10 20:17:06

问题


If I defined a variadic function:

#include <stdio.h>
#include <stdarg.h>

int f(char*s,...)
{ 
    va_list ap;
    int i=0;
    va_start(ap, s);
    while(s)
    {
       printf("%s ", s);
       i++;
       s=va_arg(ap,char*);
    }
    va_end(ap);
    return i;
}

int main()
{ 
    return f("a","b",0);
}

gcc (linux x64) compiles this and the exe runs and prints "a b ".

is there any need for a cast like:

return f("a","b",(char*)0)

on common systems?


回答1:


Your code should work fine on any system that supports the SYSV x64 ABI standard. It may work on systems that use some other ABI standard that has similar requirements, and may fail on any system that uses some other ABI1. This is all undefined according to the C standard.


1In particular, Microsoft does NOT follow the standard x64 ABI, they have their own standard.




回答2:


The compiler can't auto promote pointer for variadic parameter, for example that why when you want to print a pointer in printf you must cast it to void *:

printf("%p", (void *)ptr);

The same rule applies to all variadic functions, compiler can't know that your function expect a char *, and 0 is by default just an integer so yes you need to cast it (char *)0.


Even NULL must be cast with your function (char *)NULL


so why does main() work and when will it fail?

Your code don't really "work". Your code invoke undefined behavior, anything can happen, so no one can answer this. Here you are lucky, but next time maybe not.



来源:https://stackoverflow.com/questions/49814318/nulls-in-variadic-c-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!