C动态内存分配:(四)malloc与new分配内存大小查看函数:_msize()/malloc_usable_size

_msize()为windows下检测堆上动态分配的内存块的大小。malloc_usable_size为LINUX下进行检测的函数。

1、_msize

(1)函数原型

size_t _msize( 
   void* memblock 
);
(2)函数说明

1)参数memblock为一个堆内存块的地址。不能传入栈上的地址(例如a[10],_msize(a))

2)函数返回指针所指内存块的大小。malloc分配的函数返回的地址不包含首部,因此使用_msize()函数测得的也不包含首部大小。

(3)使用示例

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
void main( void )
{
   long *buffer;
   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: */
   if( (buffer = (long*)realloc( buffer, size + (1000 * sizeof( long )) )) ==  NULL )
      exit( 1 );
   size = _msize( buffer );
   printf( "Size of block after realloc of 1000 more longs: %u\n", 
            size );
   free( buffer );
   exit( 0 );
}
2、malloc_usable_size

(1)函数原型

扫描二维码关注公众号,回复: 3793806 查看本文章

#include "malloc.h"
size_t malloc_usable_size(void *_ptr)



猜你喜欢

转载自blog.csdn.net/zxx910509/article/details/63250653