当我们使用malloc而不声明stdlib.h头文件时,编译器返回一个int为什么? [英] When we used malloc without declaring stdlib.h header file compiler returns an int why?

查看:316
本文介绍了当我们使用malloc而不声明stdlib.h头文件时,编译器返回一个int为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前曾问过一个问题,它是

Earlier I asked one question that is if the return of malloc is cast then the error which would be flagged is hidden and I got the answer that is: In (older dialects of) C, you can call a function which hasn't been declared; that implicitly declares a function with a return type of int. So, if you were to call malloc() without including the header, you'd get code that erroneously assumed that it returned int. Without a cast, you'd get a compiler error when you tried to assign it to a pointer. With a cast, the code would compile, potentially giving obscure runtime errors and lengthy debugging sessions.

我了解到,在不包含<stdlib.h>头文件的情况下,编译器会隐式声明一个返回类型为int的函数.

I understand that without inclusion of <stdlib.h> header file compiler implicitly declares a function with a return type of int.

但是我感到困惑的是,根据创建者定义的malloc()的函数定义,只要我们使用它,它将返回void *,但是没有<stdlib.h>时它将返回int.那么它的定义如何变化,是编译器将void *隐式更改为int *类型,还是有其他原因?

But I confused in that according to malloc()'s function definition that is defined by creator, it will returns void * whenever we used it, but without <stdlib.h> it returns int. So how does its definition change, is compiler implicitly changing void * to int * type, or there is some other reason?

我知道我无法正确解释我的问题,但是如果有人理解,请向我解释一下.

I know that I couldn't explain my question properly but if anybody understand, please explain me about that.

推荐答案

对于C,所有未声明的函数都隐式声明为返回int并接受未指定数量的未指定参数.

For C, all undeclared functions are implicitly declared to return int and take an unspecified number of unspecified arguments.

malloc的问题是intvoid *的大小可能不相同,甚至不兼容.例如,在现代的64位计算机上,指针是64位类型,而int是32位类型,因此,如果没有正确的malloc声明,编译器将删除指针的高32位.指针.

The problem with malloc is that an int and a void * may not be the same size, or even compatible. For example, on modern 64-bit machines pointers are 64-bit types while int is a 32-bit type, so if you don't have a proper declaration of malloc the compiler will drop the high 32 bits of the pointer.

这篇关于当我们使用malloc而不声明stdlib.h头文件时,编译器返回一个int为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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