Emad Goahri Emad Goahri - 1 month ago 8
C Question

C programming segmentation fault for a returned pointer by a function inside another file

I have this very simple code written in C. They are in two separate files.

myFunction.c

#include <stdlib.h>

int *extFunc() {
int *a = (int *) calloc( 1, sizeof(int) );
*a = 12;
return a;
}


main.c

#include <stdio.h>
#include <stdlib.h>

int main()
{
int *p = (int *) extFunc();
int x = *p; // causes segmentation fault !
printf("%d\n", *p); // causes segmentation fault !
}


I compiled it with this command
cc myFunction.c main.c
and the output is like below

main.c:6:19: warning: implicit declaration of function 'extFunc' is invalid in C99 [-Wimplicit-function-declaration]
int *p = (int *) extFunc();
^
main.c:6:11: warning: cast to 'int *' from smaller integer type 'int' [-Wint-to-pointer-cast]
int *p = (int *) extFunc();
^
2 warnings generated.


and when I run it, it gives
Segmentation fault: 11
. What am I doing wrong?

I checked the function when it is in the main.c file and it worked. However, I need them to be separate like above.

In my original code there are struct pointers instead of integer pointers. I explained my problem here with a simplified example.

usr usr
Answer

You haven't provided a prototype for extFunc(). Create a header file with:

int *extFunc(void);

and include it in both source files.

Since the compiler can't see a prototype it assumed int as return type for extFunc() which probably truncates the address returned by calloc() on your system (probably 64bit system). But there's no implicit int rule since C99. Always include prototypes for functions and pay attention to compiler warnings.