C語言中的realloc函數的使用注意事項


最近在學C語言,在用到realloc函數時除了一些問題,始終找不到問題所在,后來便一步一步調試,終於找到了問題,由於前面calloc函數使用時將字符串的長度設置錯了,導致在使用realloc時原字符串末尾'\0'被清除了,導致了一系列的問題,好在終於解決了,現在來總結一下

  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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM