Mike Henke
Mike Henke

Reputation: 643

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.

Upvotes: 0

Views: 151

Answers (2)

abelenky
abelenky

Reputation: 64730

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.

Upvotes: 5

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

I think you mean the following

void * allocate_array( size_t member_size, size_t nmember, bool clear )
{
    return clear ? calloc( nmember, member_size ) : malloc( nmember * member_size );
}

As for your function definition then neither the call of calloc nor the call of malloc is correct.

Take into account that this if statement

   if(clear){
       // ... 
   } else if(!clear) {
       // ... 
   }

is better to write like

   if(clear){
       // ... 
   } else {
       // ... 
   }

The last record is more clear,

Upvotes: 5

Related Questions