Search code examples
cmallocrealloc

Correct way to calculate the size for malloc() and realloc()?


I've seen malloc() and realloc() used a bunch of different ways. After testing the various ways out, I was curious to know if I was using them correctly ?

First I tried

int size = rowSize * colSize;
int newSize = size + rowSize;

int *randomNum;

randomNum = malloc(size * sizeof *randomNum);

randomNum = realloc(randomNum, newSize * sizeof *randomNum);

and that works!!

Then I tried,

int size = rowSize * colSize;
int newSize = size + rowSize;

int *randomNum;

randomNum = malloc(size * sizeof(int));

randomNum = realloc(randomNum, newSize * sizeof(int));

and that works also. So I guess I don't know why I'd use sizeof *some_name versus sizeof(int) ?
Is there a reason to use one over the other?


Solution

  • They're the same. The reason to use your former example is to ease maintenance later if you decide to change types.

    That said, don't use realloc like that - if it fails, you'll leak the original randomNum allocation.