Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

c - When we used malloc without declaring stdlib.h header file compiler returns an int why?

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.

I understand that without inclusion of <stdlib.h> header file compiler implicitly declares a function with a return type of 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...