考虑这段代码:
char buffer[] = "abcdefghijklmnopqrstuvwxyz",
*val = malloc(10), *pbuf = buffer, *pval = val, *tmpbuf;
int size = 10,loaded = 0;
while(*pbuf) {
if((loaded + 1) >= size) {
size += 10;
tmpbuf = realloc(val, size);
if(tmpbuf != NULL) {
val = tmpbuf;
pval = val;
} else {
printf("realloc()\n");
exit(-1);
}
}
*pval ++= *pbuf ++;
loaded ++;
}
*pval ++= '\0';
printf("%s\n", val);
free(val);
它打印tuvwxyz
而不是abcdefghijklmnopqrstuvwxyz
.
为什么?根据文档,返回的新指针realloc()
不保留先前传递的缓冲区。