在使用realloc()重新分配内存大小的时候失败了,怎样去释放更改前的内存?


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
   char name[100];
   char *description;
 
   strcpy(name, "Zara Ali");
 
   /* 动态分配内存 */
   description = (char *)malloc( 30 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "Zara ali a DPS student.");
   }
   /* 假设您想要存储更大的描述信息 */
   description = (char *) realloc( description, 100 * sizeof(char) );//如果此处失败了,怎样释放向前的30byte的内存呢?
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcat( description, "She is in class 10th");
   }
   
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
 
   /* 使用 free() 函数释放内存 */
   free(description);//如果重新分配失败了,这里就没有地址值,不能真正的释放已经分配的内存
}

下面是我的理解,供参考:
用一个char指针保存description之前的值,然后当description再次指向新的分配内存后,如果内存分配失败,就用fre
e函数释放这个char指针指向的内存块。(参考:C Primer Plus 第六版第399页 )

 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main()
{
   char name[100];
   char *description;
 
   strcpy(name, "Zara Ali");
 
   /* 动态分配内存 */
   description = (char *)malloc( 30 * sizeof(char) );
   char * td = description;
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "Zara ali a DPS student.");
   }
  // printf("before td=%s\n",td);
  
   /* 假设您想要存储更大的描述信息 */
   description = NULL;//(char *) realloc( description, 100 * sizeof(char) );//如果此处失败了,怎样释放向前的30byte的内存呢?
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
      free(td);
      printf("after td: %s\n", td );
   }
   else
   {
      strcat( description, "She is in class 10th");
   }
   
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
 
   /* 使用 free() 函数释放内存 */
   free(description);//如果重新分配失败了,这里就没有地址值,不能真正的释放已经分配的内存
   //printf("Description: %s\n", description );

}