C 语言动态分配内存
请问我用malloc时,想为它动态分配内存,但又不想在开始就为它分配一个固定的空间,怎么办,就像new一样
[解决办法]
realloc - Reallocate memory blocks
MSDN上的例子
// crt_realloc.c
// This program allocates a block of memory for
// buffer and then uses _msize to display the size of that
// block. Next, it uses realloc to expand the amount of
// memory used by buffer and then calls _msize again to
// display the new amount of memory allocated to buffer.
#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 );
}
[解决办法]
只要你用到malloc,那就必须要指定大小,难道楼主想永远不指定固定的大小,开出随机的内存?
因为你开出的内存肯定有朝一日是不够用的,当然也可能是永远浪费的,可这没办法.
看C++里面写的vector也无法避免这个问题,只是在容量满了的时候它会自动的扩展一倍的内存,
楼主可以根据自己的需要制订一个扩展的算法
[解决办法]
malloc后记得free就OK啦,动态只是说在运行期内再决定大小,并不是说不决定大小了,要静态的嘛就直接数组好了.
堆内存分配后要记得释放,而且释放后记得把原来的指针设为NULL 不然再次不小心去free的时候就会抛异常