开发者

Why can I successfully compile a program even though a header file is missing?

I found a weird problem when I was learning the "strtok" function. At first I missed a header file when writing a demo program as follows:

/* strtok example */
#include <stdio.h>
//#include <string.h> // the header file I've 开发者_开发百科missed at first

int main ()
{
    char str[] ="- This, a sample string.";
    char * pch;
    printf ("Splitting string \"%s\" into tokens:\n",str);
    pch = strtok (str," ,.-");
    while (pch != NULL)
    {   
        printf ("%s\n",pch);
        pch = strtok (NULL, " ,.-");
    }   
    return 0;
}

The compiler didn't give any error message and successfully compiled the program. But it lead to a segmentation fault when running. And when I added the missing header file, everything went well.

My question is why the compiler didn't diagnose any errors for the first compilation. I compiled it under Mac OS X with gcc4.2.1.


In C, functions were allowed to have no prototypes (declarations). There would be no parameter conversions when calling such functions. Eg.:

f(0);

would call a function named f with a parameter (int)0 even when f was not declared. This results in undefined behavior (...segfaults...) when the actual definition of f (in another .c file, or in a library) was eg. int f(char*) or int f(long). This is not good practice, but is retained for backwards compatibility with original C.

When the prototype is present, the compiler would automatically convert parameter to required types (possibly issuing an error) at call site.

PS: don't get me wrong thinking int is the default. What the compiler actually calls is entirely dependent on the call parameters. Eg. f(1.1) would match with void f(double), f("string") with f(char*).


My question is why the compiler didn't give any error message at the first compilation.

Because you didn't compile with -Wall -Wextra. For newly-written modern code, you should be doing this as a matter of course.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜