[英]Confusion about using malloc/calloc pointer to hold the return value of realloc
有人说用原来的malloc()/calloc()指针作为保存realloc()返回值的变量是错误的。 这是一个例子:
#include <stdlib.h>
int main()
{
int *malloc_ptr = malloc(5 * sizeof(int));
malloc_ptr = realloc(malloc_ptr, 10 * sizeof(int));
return 0;
}
他们的理由是,如果 realloc() 失败,它将返回 NULL,从而使 malloc_ptr == NULL。 这将使您无法访问您使用 malloc() 请求的内存。 他们的解决方案是这样做的:
#include <stdlib.h>
int main()
{
int *malloc_ptr = malloc(5 * sizeof(int));
int *realloc_ptr = realloc(malloc_ptr, 10 * sizeof(int));
if (realloc_ptr == NULL) {
// Whatever you want to do
} else
malloc_ptr = realloc_ptr;
return 0;
}
然而,如果它们是正确的,并不意味着某些使用 malloc 指针作为 realloc() 持有者的软件可能是不正确的,因为我看到很多人使用 malloc()/calloc() 指针作为变量保存 realloc() 的返回值。 这是真的?
根据man realloc
,这将是realloc
处理的正确方式:
#include <stdlib.h>
int main()
{
int *malloc_ptr = malloc(5 * sizeof(int));
if (malloc_ptr == NULL) {
fprintf(stderr, "Could not allocate memory\n");
/* here goes error handling */
}
/* ... */
int *realloc_ptr = realloc(malloc_ptr, 10 * sizeof(int));
if (realloc_ptr == NULL) {
fprintf(stderr, "Could not reallocate memory, keeping the old allocated block\n");
/* here goes error handling */
} else {
malloc_ptr = realloc_ptr;
}
/* ... */
free(malloc_ptr);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.