简体   繁体   中英

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?

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.

After accept answer

@Carl Norum answer is good, but was mostly done with this and it adds a few points.

Use of sizeof(*pointer) or sizeof(type) is a style issue.
I find the 1st easier to maintain and less error prone. Applies for both malloc() , realloc() .

size_t count = rowSize * colSize;
int *randomNum = malloc(count * sizeof *randomNum);
int *randomNum = malloc(count * sizeof(int));

Example realloc()

int *randomNum = NULL;
...
size_t N = foo();

// If N is zero, (a strange case) one might want to increase it.
// Successfully allocating 0 bytes may return NULL or a non-NULL pointer.

int *randomNum2 = realloc(randomNum, N * sizeof(*randomNum));
if (randomNum2 == NULL && N > 0) {
  // randomNum still contains what it use to.
  Handle_allocation_failure();
  ...
  free(randomNum);
}
else {
  // The happy path
  randomNum = randomNum2;
  ...
  free(randomNum);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM