C++ 中的realloc() 函數重新分配先前分配但尚未釋放的內存塊。
realloc() 函數重新分配先前使用 malloc() 、 calloc() 或 realloc() 函數分配但尚未使用 free() 函數釋放的內存。
如果新大小為零,則返回的值取決於庫的實現。它可能會也可能不會返回空指針。
realloc()原型
void* realloc(void* ptr, size_t new_size);
該函數在<cstdlib> 頭文件中定義。
參數:
ptr
:指向要重新分配的內存塊的指針。new_size
:一個無符號整數值,表示內存塊的新大小(以字節為單位)。
返回:
realloc() 函數返回:
- 指向重新分配的內存塊開頭的指針。
- 如果分配失敗,則為空指針。
在重新分配內存時,如果內存不足,則不釋放舊內存塊並返回空指針。
如果舊指針(即 ptr)為空,則調用 realloc() 與調用 malloc() 函數相同,並將新大小作為其參數。
有兩種可能的重新分配內存的方法。
- 擴展或收縮同一個塊:如果可能,舊指針(即 ptr)指向的內存塊被擴展或收縮。內存塊的內容保持不變,直到新舊大小中的較小者。如果該區域被擴展,新分配的塊的內容是未定義的。
- 搬到新位置: 分配一個大小為new_size 字節的新內存塊。在這種情況下,內存塊的內容也保持不變,直到新舊大小中的較小者,如果內存擴大,新分配的塊的內容是未定義的。
示例 1:realloc() 函數如何工作?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
float *ptr, *new_ptr;
ptr = (float*) malloc(5*sizeof(float));
if(ptr==NULL)
{
cout << "Memory Allocation Failed";
exit(1);
}
/* Initializing memory block */
for (int i=0; i<5; i++)
{
ptr[i] = i*1.5;
}
/* reallocating memory */
new_ptr = (float*) realloc(ptr, 10*sizeof(float));
if(new_ptr==NULL)
{
cout << "Memory Re-allocation Failed";
exit(1);
}
/* Initializing re-allocated memory block */
for (int i=5; i<10; i++)
{
new_ptr[i] = i*2.5;
}
cout << "Printing Values" << endl;
for (int i=0; i<10; i++)
{
cout << new_ptr[i] << endl;
}
free(new_ptr);
return 0;
}
運行程序時,輸出將是:
Printing Values 0 1.5 3 4.5 6 12.5 15 17.5 20 22.5
示例 2:realloc() 函數,new_size 為零
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int *ptr, *new_ptr;
ptr = (int*) malloc(5*sizeof(int));
if(ptr==NULL)
{
cout << "Memory Allocation Failed";
exit(1);
}
/* Initializing memory block */
for (int i=0; i<5; i++)
{
ptr[i] = i;
}
/* re-allocating memory with size 0 */
new_ptr = (int*) realloc(ptr, 0);
if(new_ptr==NULL)
{
cout << "Null Pointer";
}
else
{
cout << "Not a Null Pointer";
}
return 0;
}
運行程序時,輸出將是:
Null Pointer
示例 3:當 ptr 為 NULL 時的 realloc() 函數
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main()
{
char *ptr=NULL, *new_ptr;
/* reallocating memory, behaves same as malloc(20*sizeof(char)) */
new_ptr = (char*) realloc(ptr, 50*sizeof(char));
strcpy(new_ptr, "Welcome to Programiz.com");
cout << new_ptr;
free(new_ptr);
return 0;
}
運行程序時,輸出將是:
Welcome to Programiz.com
相關用法
- C++ real()用法及代碼示例
- C++ regex_iterator()用法及代碼示例
- C++ remainder()用法及代碼示例
- C++ remquo()用法及代碼示例
- C++ rename()用法及代碼示例
- C++ rewind()用法及代碼示例
- C++ remove()用法及代碼示例
- C++ rename用法及代碼示例
- C++ rint(), rintf(), rintl()用法及代碼示例
- C++ rotate用法及代碼示例
- C++ ratio_less_equal()用法及代碼示例
- C++ rint()用法及代碼示例
- C++ ratio_less()用法及代碼示例
- C++ round()用法及代碼示例
- C++ raise()用法及代碼示例
- C++ ratio_greater()用法及代碼示例
- C++ ratio_not_equal()用法及代碼示例
- C++ ratio_greater_equal()用法及代碼示例
- C++ ratio_equal()用法及代碼示例
- C++ unordered_map cbegin用法及代碼示例
注:本文由純淨天空篩選整理自 C++ realloc()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。