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

    技术2022-05-20  33

    #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


    最新回复(0)