On Wed, 19 Oct 2005 18:01:33 -0000, mark < XXXX@XXXXX.COM > wrote in
Add this and try compiling it again:
You shouldn't be casting the return value of malloc() in C. Why are
you using the cast? I bet it is because you get a compiler error if
Yes, absolutely. "implicit declaration" means that you do not have a
prototype or declaration in scope. Under versions of the C language
standard (prior to 1999), the compiler automatically assumes the
function you are calling returns an int and pretty much takes whatever
arguments you pass to it. Since malloc() returns a pointer to void,
and not an int, the compiler complains if you try to assign the return
value to a pointer. So you add the cast to shut up to compiler.
What is wrong is that your program generates undefined behavior. You
are lying to your compiler. By not including a prototype for
malloc(), you are telling the compiler that malloc() returns an int.
But it does not.
On many platforms, where int and void* happen to be the same size, and
the compiler returns them from functions the same way, this undefined
behavior seems to "work", but it is still wrong. On some processors,
even if int and void* are the same size, they are returned in
different registers, address registers versus data registers, this
will always crash horribly.
And when you upgrade the operating system you are using from 32 bits
to 64 bits, this is almost guaranteed to fail.
Include <stdlib.h> so you have a proper prototype for malloc() in
scope, and remove the cast on the return value.
And no, this did not "work" with gcc 3.3.6. You created undefined
behavior and it just so happened that it did what you wanted to do.
That did not make it correct.
comp.lang.c.moderated - moderation address: XXXX@XXXXX.COM -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.