Tuesday, March 9, 2010

Implicit Declaration of function in C - Segmentation fault

This warning is very common in C programs. Usually we can neglect it but it can cost you dear if you have it without notice. I learned it the hard way that warnings should be debugged from a code. I now always compile my programs with -Wall flag to see each and every warning.

There are two main reasons for this warning.
1) Header file not included
    Try writing a program that uses malloc function and do not include stdlib.h in your code. You will see this warning. The solution is simple, just add
#include <stdlib.h >
in your code and you are good to go.

2) Prototype mismatch
This one is a tricky one. I remember when I was working on my research project I had a bunch of these errors for the functions I created myself. I knew there was nothing else needed as those were my functions. Moreover, I had the prototypes there at the top. The issue was that these functions were declared in a different file called util.c, that file resided at the same path though. I had a different way of writing prototypes and declarations. For example look at this function:

void *myfunc(para1, para2)
int  para1;
char *para2;


This is a valid way of writing a function and it is fine to use a prototype like:
extern void *myfunc();
at the top of this file. However, if this function is declared in some other file then this will cause you a warning. Instead of explaining the details I would say just change the prototype to something like this:
extern void *myfunc(int para1, int para2);
and you will see why your program was throwing segmentation faults.

No comments:

Post a Comment