【发布时间】:2014-03-29 09:33:33
【问题描述】:
我正在编写一个文件复制程序,在该程序中我遇到了关于 realloc() 的困难。 请看下面的 sn-p(我写它是为了理解 realloc() 的工作原理):-
int main(){
char *p =(char *) malloc ( 10 ),*t;
p = "this is";
if (strlen (p)==7)
{
t = realloc ( p,14);
if ( t==NULL)
{
printf ("no no\n");
}
}
printf("%p\n%p\n%d",p,t,strlen(p));
free (p);
free (t);
return 1;
}
输出
no no //because realloc () is unable to reallocate the memory
00450357 //address of p
00000000 //address of t
那么为什么 realloc() 无法重新分配内存并将其(其地址)分配给t?
编辑 我在 Windows 中使用代码块。
【问题讨论】:
-
因为你已经用字符串赋值破坏了 malloc 返回的地址。如果你使用了 strcpy,那么 realloc 会起作用,但你会在 free(p) 上获得双重释放,因为它已经在 realloc 期间被释放。