realloc困惑

昨天,在做自己的东西的时候,一个内存错误,折腾了我大半天,吗的,想起来真的非常气人,就那么一个小小的错误,居然能把我卡住这么久,是一个什么错误呢,就是一个realloc函数。

首先我们来看一下这个函数的声明,MSDN上面是如下描述的:

realloc

Reallocate memory blocks.

void *realloc( void *memblock, size_t size );

 

Return Value

realloc returns a void pointer to the reallocated (and possibly moved) memory block. The return value is NULL if the size is zero and the buffer argument is not NULL, or if there is not enough available memory to expand the block to the given size. In the first case, the original block is freed. In the second, the original block is unchanged. The return value points to a storage space that is guaranteed to be suitably aligned for storage of any type of object. To get a pointer to a type other than void, use a type cast on the return value.

Parameters

memblock

Pointer to previously allocated memory block

size

New size in bytes

Remarks

The realloc function changes the size of an allocated memory block. The memblock argument points to the beginning of the memory block. If memblock is NULL, realloc behaves the same way as malloc and allocates a new block of size bytes. If memblock is not NULL, it should be a pointer returned by a previous call to calloc, malloc, or realloc.

The size argument gives the new size of the block, in bytes. The contents of the block are unchanged up to the shorter of the new and old sizes, although the new block can be in a different location. Because the new block can be in a new memory location, the pointer returned by realloc is not guaranteed to be the pointer passed through the memblock argument.

上面的这些话中,就是没有提到memblock不能是没有初始化的变量,既然他没说我也就没注意,知道后来调试程序的时候才知道,这个变量必须是要初始化了的值,即使是NULL也是可以的,相当于malloc,之后在程序中改了之后就可以正常运行了,汗!

你可能感兴趣的:(function,null,buffer,UP)