计算 malloc() 和 realloc() 大小的正确方法?

问题描述 投票:0回答:2

我见过

malloc()
realloc()
使用了很多不同的方式。在测试了各种方法之后,我很好奇我是否正确使用了它们?

我首先尝试过

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

int *randomNum;

randomNum = malloc(size * sizeof *randomNum);

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

那行得通!!

然后我尝试了,

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

int *randomNum;

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

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

这也有效。所以我想我不知道为什么我会使用

sizeof *some_name
而不是
sizeof(int)

有理由使用其中一种而不是另一种吗?

c malloc realloc
2个回答
4
投票

它们是一样的。使用前一个示例的原因是,如果您决定更改类型,可以方便以后的维护。

也就是说,不要像那样使用

realloc
- 如果失败,你将泄漏原始的
randomNum
分配。


1
投票

接受答案后

@Carl Norum 的答案很好,但主要是用这个完成的,它增加了几点。

使用

sizeof(*pointer)
sizeof(type)
是风格问题。
我发现第一个更容易维护并且不易出错。适用于
malloc()
realloc()

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

示例

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.