据我所关注的,如果realloc
失败,我们失去设置缓冲区(指针)的信息和对realloc
NULL
我们为什么要使用`realloc`如果我们需要一个'TMP buffer`
去考虑下面的程序:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void){
char *ptr = malloc(256);
if (!ptr){
printf("Error, malloc\n");
exit(1);
}
strcpy(ptr, "Michi");
ptr = realloc (ptr, 1024 * 102400000uL); /* I ask for a big chunk here to make realloc to fail */
if (!ptr){
printf("Houston we have a Problem\n");
}
printf("PTR = %s\n", ptr);
if (ptr){
free(ptr);
ptr = NULL;
}
}
当然的输出是:
Houston we have a Problem
PTR = (null)
我只是失去了内部ptr
的信息。
现在要解决这个问题,我们应该先使用一个临时缓冲区(指针)来查看我们是否获得了这块内存,如果我们能够得到它,我们可以使用它,如果没有,我们仍然有主缓冲区(指针)安全。
现在请考虑下面的程序,在那里,而不是调用realloc
我打电话malloc
在临时缓冲区(指针):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void){
char *ptr = malloc(256);
char *tmpPTR = NULL;
if (!ptr){
printf("Error, malloc\n");
exit(1);
}
strcpy(ptr, "Michi");
tmpPTR = malloc (1024 * 102400000uL);
if (tmpPTR){
strcpy(tmpPTR, ptr);
strcat(tmpPTR, " - Aloha");
if (ptr){
free(ptr);
ptr = NULL;
}
}else{
printf("Malloc failed on tmpPTR\n\n");
}
if (ptr){
printf("PTR = %s\n", ptr);
free(ptr);
ptr = NULL;
}else if (tmpPTR){
printf("tmpPTR = %s\n", tmpPTR);
free(tmpPTR);
ptr = NULL;
}
}
,输出是:
Malloc failed on tmpPTR
PTR = Michi
现在我为什么要曾经使用realloc
? 根据这种情况使用realloc
而不是malloc
有什么好处吗?
你的假设是错误的。如果['realloc()'](http://man7.org/linux/man-pages/man3/realloc.3.html)失败,它会返回NULL,但缓冲区不变(仍然完全有效使用)。你只是做错了。改用临时指针。 –
是的,我的意思是直接分配,但我仍然需要一个tmpBuffer。那么为什么我应该使用Realloc?这是问题。 – Michi
下载选民请解释一下? – Michi