Search code examples
cmallocdynamic-allocation

Using malloc correctly


I'm trying to refresh my C skills. Let's say I'm trying to perform a malloc and a calloc:

void* allocate_array(size_t member_size, size_t nmember,bool clear)
       if(clear){
            void *cal = calloc(nmember, sizeof(member_size));
            return cal;
       } else if(!clear) {
            void *mal = (void *)malloc(sizeof(member_size));
            return mal;
       }

I think I'm using calloc correctly here but I am unsure if I am using malloc correctly. It confuses me when I need to return void.


Solution

  • You are doing it wrong in both cases: malloc and calloc.

    malloc will allocate the number of bytes you tell it to.

    You call malloc(sizeof(member_size)):
    Variable member_size has type size_t (more-or-less an int).
    sizeof(size_t) is 4-bytes (on many platforms).
    So, sizeof(member_size) is 4-bytes, and you are calling malloc(4).

    I don't think you want 4 bytes.
    I think you want malloc(nmember * member_size)


    Similarly, for calloc, you want: calloc(nmember, member_size)

    I don't know why you're throwing in random sizeof calls for no good reason.