Results 1 to 3 of 3

Thread: [C99] A question about malloc()

  1. #1
    Join Date
    Oct 2013

    [C99] A question about malloc()


    If I do something like this:
    int *array = (int*) malloc(sizeof(int) * randomnumber);
    Does it mean that malloc creates an... lets say 'continuous' block of memory for this array? I mean, when I do something like
    int *var = array+1;
    *var = 5;
    Can i be sure that It won't explode and save 5 in my array?
    Last edited by ppplayer80; January 23rd, 2014 at 07:10 PM.

  2. #2
    Join Date
    Aug 2011
    47°9′S 126°43W
    Kubuntu 14.04 Trusty Tahr

    Re: [C99] A question about malloc()

    • The block isn't created but allocated. This looks pedantic, but in some cases you have to remember that there is only so much memory to allocate.
    • Do not cast the returned value of malloc(). malloc() returns a "void*", a pointer to anything that fits any typed pointer without a cast. When you cast you run the risk to not notice that you forgot to declare malloc() properly (because the compiler will think it returns an int, and with a cast it won't warn you about assigning the int to a pointer)
    • Yes, the allocated block is continuous, so all pointers from the origin to the origin+allocated size-1(*) correspond to usable memory locations.

    (*) using the pointer arithmetic semantics, adding N to the pointer moves it (N * size_of_type_pointed_to) bytes.
    Warning: unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.

  3. #3
    Join Date
    Nov 2005
    Bordeaux, France
    Ubuntu 12.04 Precise Pangolin

    Re: [C99] A question about malloc()

    Quote Originally Posted by ppplayer80 View Post
    Can i be sure that It won't explode and save 5 in my array?
    Yes... assuming randomnumber >= 2.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts