C语言中的realloc函数的使用注意事项

最近在学C语言,在用到realloc函数时除了一些问题,始终找不到问题所在,后来便一步一步调试,终于找到了问题,由于前面calloc函数使用时将字符串的长度设置错了,导致在使用realloc时原字符串末尾''被清除了,导致了一系列的问题,好在终于解决了,现在来总结一下

  realloc使用注意事项(这是总结网友们的经验)

1. realloc失败的时候,返回NULL

2. realloc失败的时候,原来的内存不改变,也就是不free或不move,(这个地方很容易出错)

3. 假如原来的内存后面还有足够多剩余内存的话,realloc的内存=原来的内存+剩余内存,realloc还是返回原来内存的地址; 假如原来的内存后面没有足够多剩余内存的话,realloc将申请新的内存,然后把原来的内存数据拷贝到新内存里,原来的内存将被free掉,realloc返回新内存的地址

4. 如果size为0,效果等同于free()
5. 传递给realloc的指针必须是先前通过malloc(), calloc(), 或realloc()分配的 

MSDN上  

Return Value

realloc returns a void pointer to the reallocated (and possibly moved) memory block.

If there is not enough available memory to expand the block to the given size, the original block is left unchanged, and NULL is returned.

If size is zero, then the block pointed to by memblock is freed; the return value is NULL, and memblock is left pointing at a freed block.

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

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

原文地址:https://www.cnblogs.com/TB-Go123/p/4229720.html