Realloc函数及其使用注意事项

6530阅读 1评论2013-01-28 dyli2000
分类:C/C++

1、Realloc函数功能说明

Realloc函数的功能比malloc和calloc函数更丰富,可以实现内存分配和内存释放的功能,函数原型如下:

void *realloc(void *p,int n);

其中,指针p必须为指向堆内存空间的指针,即必须由malloc函数和calloc函数或者realloc函数分配空间的指针。

先判断当前的指针是否有足够的连续空间,如果有,扩大mem_address指向的地址,并且将mem_address返回;

如果空间不够,先按照newsize指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来mem_address所指内存区域,同时返回新分配的内存区域的首地址。即重新分配存储器块的地址。

realloc函数分配的空间也是未初始化的。

 

2、案例一、

#include "stdafx.h" 
#include  
#include  
#include 
int main( void ) 
{ 
   long *buffer, *oldbuffer; 
   size_t size;
   if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL ) 
      exit( 1 );
   size = _msize( buffer ); 
   printf_s( "Size of block after malloc of 1000 longs: %u,buffer addr=%p\\n", size,buffer );
   // Reallocate and show new size: 
   oldbuffer = buffer;     // save pointer in case realloc fails 
   if( (buffer = (long*)realloc( buffer, size + (1000 * sizeof( long )) )) ==  NULL ) 
   { 
      free( oldbuffer );  // free original block 
      exit( 1 ); 
   } 
   size = _msize( buffer ); 
   printf_s( "Size of block after realloc of 1000 more longs: %u,buffer addr=%p\\n", size,buffer );
   free( buffer );          // Other way to release it: realloc(p,0),p=NULL 
   getchar(); 
   exit( 0 ); 
}

image

3、案例二、

#include "stdafx.h" 
#include  
#include 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    int *p = NULL; 
    p = (int *)malloc(sizeof(int)); 
    *p  = 3; 
    printf(" p = %p \\n",p); 
    printf(" p = %d \\n",*p);
    p = (int*)realloc(p,10*sizeof(int)); 
    printf(" p = %p \\n",p); 
    printf(" p = %d \\n",*p);
    p = (int*)realloc(p,100*sizeof(int)); 
    printf(" p = %p \\n",p); 
    printf(" p = %d \\n",*p);
    // 释放P指向的空间,特别注意!这里没有用Free 
    realloc(p,0); 
    p = NULL; 
    getchar(); 
    return 0; 
}

image

 

综合注意点:

使用malloc,calloc,realloc函数分配的内存空间都要使用Free函数或者指针参数为NULL的realloc函数来释放。

上一篇:calloc函数使用注意事项
下一篇:如何变得更聪明?看这46招

文章评论