C++ realloc()用法及代码示例
C++ 中的realloc() 函数重新分配先前分配但尚未释放的内存块。
realloc() 函数重新分配先前使用 malloc() 、 calloc() 或 realloc() 函数分配但尚未使用 free() 函数释放的内存。
如果新大小为零,则返回的值取决于库的实现。它可能会也可能不会返回空指针。
realloc()原型
void* realloc(void* ptr, size_t new_size);
该函数在
参数:
返回:
示例 1:realloc() 函数如何工作?
- #include
- #include
- 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
- #include
- 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
- #include
- #include
- 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