您的位置:首页 > 编程语言 > C语言/C++

怎么查看动态分配内存空间的大小(c语言)

2011-03-02 11:10 218 查看
#include <stdio.h>

#include <malloc.h>

#include <stdlib.h>

int main( void )

{

long *buffer, *oldbuffer;

size_t size;

if( (buffer = (long *)malloc( 1000 * sizeof( long ) )) == NULL )

exit( 1 );

size = _msize( buffer );

printf( "Size of block after malloc of 1000 longs: %u/n", size );

// Reallocate and show new size:

oldbuffer = buffer; // save pointer in case realloc fails

if( (buffer = realloc( buffer, size + (1000 * sizeof( long )) ))

== NULL )

{

free( oldbuffer ); // free original block

exit( 1 );

}

size = _msize( buffer );

printf( "Size of block after realloc of 1000 more longs: %u/n",size );

free( buffer );

exit( 0 );

}

执行结果:

Size of block after malloc of 1000 longs: 4000

Size of block after realloc of 1000 more longs: 8000

Press any key to continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: