为什么编译器假定的malloc返回一个int? [英] Why does the compiler assume that malloc returns an int?

查看:156
本文介绍了为什么编译器假定的malloc返回一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,在C它是永远不会投的返回值malloc的最佳实践()。我读过,编译器假定的malloc()返回一个int,如果你不包括文件stdlib.h 。当然,如果你想一个int隐式分配到的东西,这不是一个int它会产生一个错误,但错误可能是由一个明确的转换被掩盖 - 明确地铸造的malloc因此危险()

I'm aware that in C it's best practice to never cast the return value of malloc(). I've read that the compiler assumes that malloc() returns an int if you don't include stdlib.h. Of course it would produce an error if you tried to implicitly assign an int to something that's not an int, but that error could be covered up by an explicit cast -- hence the danger of explicitly casting malloc().

有关我创建的任何功能,如果功能不存在,则编译器会告诉我的。为什么编译器假定的malloc()返回int即使你不包括文件stdlib.h ?不应该的malloc()只是仍然不确定,直到你包括文件stdlib.h

For any function I've created, if the function doesn't exist then the compiler will tell me so. Why does the compiler assume that malloc() returns int even if you haven't included stdlib.h? Shouldn't malloc() just remain undefined until you include stdlib.h?

推荐答案

其实,如果编译器还没有看到一个声明任何函数调用(不只是malloc的),它会假设它是的extern 并返回 INT 。我只用大多数编译器给出这方面的警告,而不是一个错误,除非你打开了警戒线。

Actually, if the compiler hasn't seen a declaration for any function you call (not just malloc) it will assume it is extern and returns an int. Most compilers I've used only give a warning for this, not an error, unless you turn up the warning level.

这又回到了C的初期,我不认为这是允许在C99。

This goes back to the early days of C, I don't think this is allowed in C99.

@迈克尔的评论:你似乎是正确的,根据K&安培; R(第72页):

@Michael's comment: You seem to be correct, according to K&R (page 72):

如果在离pression发生时尚未pviously声明$ P $一个名字,随后是一个左括号,它是由上下文宣布为一个函数名,则假定该函数返回int ,并没有假定有关它的参数。

If a name that has not been previously declared occurs in an expression and is followed by a left parenthesis, it is declared by context to be a function name, the function is assumed to return an int, and nothing is assumed about its arguments.

这篇关于为什么编译器假定的malloc返回一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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