realloc() 函数重新分配先前使用 malloc()、calloc() 或 realloc() 函数分配但尚未被 free() 函数释放的内存。
如果新大小为零,则返回的值取决于库的实现。它可能返回也可能不返回空指针。
realloc() 原型
void* realloc(void* ptr, size_t new_size);
该函数定义在 <cstdlib> 头文件中。
realloc() 参数
- ptr:指向待重新分配的内存块的指针。
- new_size:一个无符号整型值,表示内存块的新大小(以字节为单位)。
realloc() 返回值
realloc() 函数返回
- 指向重新分配的内存块开头的指针。
- 如果分配失败,则返回空指针。
在重新分配内存时,如果内存不足,则不会释放旧内存块,并返回一个空指针。
如果旧指针(即 ptr)为空,则调用 realloc() 等同于调用 malloc() 函数,并将 new_size 作为其参数。
重新分配内存有两种可能的方式。
- 扩展或收缩同一块内存:如果可能,扩展或收缩由旧指针(即 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:new_size 为零时的 realloc() 函数
#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