Why do I get a warning every time I use malloc?

2019-01-06 11:06发布

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’

4条回答
倾城 Initia
2楼-- · 2019-01-06 11:24

You need to add:

#include <stdlib.h>

This file includes the declaration for the built-in function malloc. If you don't do that, the compiler thinks you want to define your own function named malloc and it warns you because:

  1. You don't explicitly declare it and
  2. There already is a built-in function by that name which has a different signature than the one that was implicitly declared (when a function is declared implicitly, its return and argument types are assumed to be int, which isn't compatible with the built-in malloc, which takes a size_t and returns a void*).
查看更多
Explosion°爆炸
3楼-- · 2019-01-06 11:26

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

#include <stdlib.h>

If you don't include this header file, the function is not known to the compiler. So it sees it as undeclared.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-01-06 11:29

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.

查看更多
该账号已被封号
5楼-- · 2019-01-06 11:41

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

查看更多
登录 后发表回答