In article <sl************ ********@nospam .com>,
Anton Dec <an******@maili nator.comwrote:
[I trust that isn't your real name.]
>malloc is defined in stdlib.h, right?
But if I write a program without #include<stdlib .hand use malloc, it
still works as expected.
Why is this? Is malloc automatically linked from somewhere else
magically?
Luck. Whether bad or good is a matter of opinion.
malloc() is not *defined* in stdlib.h, it's *declared* there. That
is, the types of its arguments and return values are specified. It's
definition is somewhere in the implementation, probably a library
that's linked with every program. Functions don't need to be declared
for linkers to find them in the library.
But if you don't declare it, things may go wrong. It will be assumed
to return int, when in fact it returns a void * pointer, so you may
get the wrong return value if ints and pointers are of different sizes
or are returned in different ways. The argument you pass to it will
be subject to the "default promotions", which means that for non-huge
values it will get passed as an int, when the argument should be of
type size_t. If int is smaller than size_t, malloc() may get the
wrong value.
It's worked for you because you are no doubt using a system where ints
and pointers are the same internally, and size_t is the same size as
int. There are an increasing number of systems where this isn't true
- commonly ones where pointers are size_t are 64 bits while int is 32.
So don't do it. You compiler should be giving you a warning; don't
ignore it.
-- Richard
--
"Considerat ion shall be given to the need for as many as 32 characters
in some alphabets" - X3.4, 1963.