-
malloc question
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*/
free(intp);
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 (:
Ian
-
I got a fix...
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
-
> 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.
-
thanks much
Thanks much Salem, I included stdlib.h and removed the cast and it worked great...
You're up a bit early eh?
Thanks again (:
Ian