Thread: malloc question

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    21

    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

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    21

    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

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > 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.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    21

    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc + segmentation fault
    By ch4 in forum C Programming
    Replies: 5
    Last Post: 04-07-2009, 03:46 PM
  2. another do while question
    By kbpsu in forum C++ Programming
    Replies: 3
    Last Post: 03-23-2009, 12:14 PM
  3. Alternative to malloc
    By stellastarr in forum C Programming
    Replies: 13
    Last Post: 04-30-2007, 04:10 PM
  4. malloc, calloc question
    By chen1279 in forum C Programming
    Replies: 12
    Last Post: 09-07-2006, 05:54 PM
  5. Question about malloc()
    By cdalten in forum C Programming
    Replies: 6
    Last Post: 05-12-2006, 10:57 AM