为什么每次使用 malloc 时都会收到警告? [英] Why do I get a warning every time I use malloc?

查看:38
本文介绍了为什么每次使用 malloc 时都会收到警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在代码中使用 malloc:

If I use malloc in my code:

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

我从 gcc 得到这个警告:

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’

推荐答案

您需要添加:

#include <stdlib.h>

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

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. 您没有明确声明它
  2. 已经有一个同名的内置函数,它的签名与隐式声明的函数不同(当一个函数被隐式声明时,它的返回和参数类型被假定为 int,它与内置的 malloc 不兼容,它接受一个 size_t 并返回一个 void*).
  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*).

这篇关于为什么每次使用 malloc 时都会收到警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆