Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6005092
  • 博文数量: 2759
  • 博客积分: 1021
  • 博客等级: 中士
  • 技术积分: 4091
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-11 14:14
文章分类

全部博文(2759)

文章存档

2019年(1)

2017年(84)

2016年(196)

2015年(204)

2014年(636)

2013年(1176)

2012年(463)

分类: C/C++

2013-01-30 13:07:30

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函数来释放。

阅读(2409) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~