views:

2496

answers:

5

If I use malloc in my code:

int *x = malloc(sizeof(int));

I get this warning from gcc:

new.c:7: warning: implicit declaration of function ‘malloc’
new.c:7: warning: incompatible implicit declaration of built-in function ‘malloc’

I'm new to C. Am I doing something wrong?

+13  A: 

You haven't done #include <stdlib.h>.

chaos
+9  A: 

You need to include the header file that declares the function, for example:

#include <stdlib.h>
andri
+9  A: 

You need to #include <stdlib.h> which includes malloc's declaration. If you don't do that, the compiler thinks you want to define your own function named malloc (and it warns you because a) you don't explicitly declare it and b) there already is a built-in function by that name).

sepp2k
+1 for an actual description of the message
Joachim Sauer
A: 

malloc has type (void*) and you want (int*) so it's better to add typecast in addition to include

#include <stdlib.h>
int *x = (int*)malloc(sizeof(int));
Evgeny
If you used malloc with C++, that cast would be necessary. Unless your code is also intended to be compiled with a C++ compiler, there are good arguments for omitting the cast, not least of which is that it is unnecessary in C.
Jonathan Leffler
Not to mention that he wouldn't have gotten the warning that there was no prototype for malloc() in scope.
John Bode
i think with wall pedantic you will get warnings without the cast. I just like silent compilations.
Evgeny
@Evgeny: If your compiler gives a warning without the cast, but with the include then I don't think you have a very good compiler. The cast is unnecessary and on many compilers would suppress an important warning due to implicit declaration of `malloc` if the correct header file is omitted.
Charles Bailey
+3  A: 

make a habit of looking your functions up in help.

most help for C is modelled on the unix manual pages.

man malloc

gives pretty useful results.

googling man malloc will show you what I mean.

of course in unix you also get apropos for things that are related.

Tim Williscroft