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,之后在程序中改了之后就可以正常运行了,汗!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值