View Full Version : malloc question

10-12-2001, 10:21 PM
I haven't done much with memory allocation, and I'm getting a warning from gcc when I try and compile it, it says "warning: assignment makes pointer from integer without a cast"

/*These are the relevant parts*/
int * intp;
intp = malloc(3*sizeof(int)); /*This is the line it is complaining about*/

I read the man on malloc and it says it returns a pointer, is there something I should be doing differentlly? In order to get rid of the warning?
Thanks for any help (:


10-12-2001, 11:24 PM
Nevermind I got a fix (: thanks anyhow

it was:

intp = (int*)malloc(3*sizeof(int));

still a bit curious though, do you guys usually cast it as whatever type of pointer it is? or do you do it differently?

(: Ian

10-13-2001, 12:44 AM
> intp = (int*)malloc(3*sizeof(int));
This is a perfect example of why casting the result of malloc is wrong.
The cast merely hides the problem.

> "warning: assignment makes pointer from integer without a cast"
Because you haven't included stdlib.h (where malloc is declared), the compiler has created implicitly the declaration
int malloc();

This then immediately breaks when you try and assign the result to a pointer (hence the pointer from integer without a cast).

If you remove the cast, and include stdlib.h, all will be well.

10-13-2001, 01:31 AM
Thanks much Salem, I included stdlib.h and removed the cast and it worked great...

You're up a bit early eh?

Thanks again (: