web网站开发基础网络推广的好处
C++ realloc()用法及代码示例
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 Net188.com");cout << new_ptr;free(new_ptr);return 0; }
运行程序时,输出将是:
Welcome to Net188.com