为什么每次使用malloc时都会收到警告?

时间:2009-08-04 23:15:42

标签: c gcc malloc warnings sizeof

如果我在代码中使用malloc

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

我从gcc收到此警告:

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

5 个答案:

答案 0 :(得分:220)

您需要添加:

#include <stdlib.h>

此文件包含内置函数malloc的声明。如果你不这样做,编译器认为你想要定义你自己的名为malloc的函数,它会警告你,因为:

  1. 您没有明确声明
  2. 该名称已有一个内置函数,其签名与隐式声明的函数不同(当隐式声明函数时,其返回和参数类型假定为int,与内置malloc不兼容,内置size_t并返回void*。)

答案 1 :(得分:30)

您尚未完成#include <stdlib.h>

答案 2 :(得分:16)

您需要包含声明该函数的头文件,例如:

#include <stdlib.h>

如果不包含此头文件,则编译器不知道该函数。所以它认为它是未宣布的。

答案 3 :(得分:10)

养成在帮助中查找你的功能的习惯。

C的大部分帮助都是在unix手册页上建模的。

man malloc

给出了非常有用的结果。

google man malloc会告诉你我的意思。

当然,在unix中你也可以得到相关的东西。

答案 4 :(得分:0)

除了其他非常好的答案之外,我还想做一点点总结,并介绍其他答案中尚未讨论的内容。


在Linux上,要在代码中使用 path('<int:classid>/<int:subjectid>/', views.mlat, name = 'mlat'), path('<int:classid>/<int:subjectid>/addmark/', views.addmark, name = 'addmark')

您实际上不必 SELECT b0_.id AS id_0, b0_.content AS content_1, b0_.slug AS slug_3 FROM blog b0_ WHERE b0_.slug = "highest peak" SELECT i0_.id AS id_0, i0_.src AS src_1 FROM image i0_ WHERE i0_.blog_id = "highest peak" ORDER BY i0_.id ASC LIMIT 30

(尽管malloc()的使用非常普遍,而且可能每个非玩具程序都应以任何一种方式包括它,因为它提供了许多有用的C标准库函数和宏)

您也可以改为#include <stdlib.h>

但是请注意,不建议使用stdlib.h,它会使您的代码不可移植。如果您想使用#include <malloc.h>,则应该永远使用malloc.h。(出于明确的原因,除非另有明确说明)。

为什么为什么在此问题的答案中得到最好的解释:

difference between <stdlib.h> and <malloc.h>

相关问题