首页 > 其他分享 >34 -realloc()函数

34 -realloc()函数

时间:2024-08-11 22:23:12浏览次数:10  
标签:函数 realloc 34 内存 new ptr block size

文章目录

1 函数原型

realloc():重新分配内存块,函数原型如下:

void* realloc (void* ptr, size_t size);

cstdlib库描述如下:

Reallocate memory block
1. Changes the size of the memory block pointed to by ptr.
2. The function may move the memory block to a new location (whose address is returned by the function).
3. The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved to a new location. If the new size is larger, the value of the newly allocated portion is indeterminate.
4. In case that ptr is a null pointer, the function behaves like malloc, assigning a new block of size bytes and returning a pointer to its beginning.
5. C90 (C++98)C99/C11 (C++11) : Otherwise, if size is zero, the memory previously allocated at ptr is deallocated as if a call to free was made, and a null pointer is returned.
6. If the function fails to allocate the requested block of memory, a null pointer is returned, and the memory block pointed to by argument ptr is not deallocated (it is still valid, and with its contents unchanged).
  1. realloc()函数:
    (1)用于重新分配内存块的大小,主要用于扩展已分配的内存块;
    (2)重分配成功且原地扩展,realloc()函数返回与原始ptr相同的指针;在这种情况下,原始ptr仍然有效,它指向的是扩展后的新内存块;
    (3)重分配成功且异地扩展,realloc()函数会分配一个新的内存块,将原内存块的内容复制到新内存块中,然后释放原内存块,即free(ptr);此时,realloc()函数返回一个指向新内存块的指针,你必须更新你的指针,以便通过新指针访问新内存块;
    (4)如果重分配失败,realloc()函数返回NULL;此时,ptr指向的原内存块不会被自动释放,它仍然有效,其内容保持不变;
    (5)如果指针ptr是一个空指针NULL,那么realloc()函数的行为和malloc()函数一样,它会分配一个新的内存块,大小为size字节,并返回指向该内存块起始位置的指针;
  2. 注意事项
    (1)内存泄漏:当重分配失败时,原内存块不会被释放,如果你不再需要原内存块,必须手动释放它,防止内存泄漏;
    (2)指针更新:首先,将realloc()函数的返回值赋给一个临时指针;其次,判断临时指针是否为空指针NULL来确定重分配内存是否成功;最后,在确认重分配内存成功的情况下,将临时指针赋值给ptr;
    (3)新内存内容:新分配的内存(即超出原内存大小的部分)是未初始化的,值是不确定的。

2 参数

realloc()函数有两个参数ptr和size:

  1. 参数ptr是一个指向原内存块的指针,类型为void*;
  2. 参数size是新内存块的大小,类型为size_t。

cstdlib库描述如下:

ptr
1. Pointer to a memory block previously allocated with malloc, calloc or realloc.
2. Alternatively, this can be a null pointer, in which case a new block is allocated (as if malloc was called).

size
1. New size for the memory block, in bytes.
2. size_t is an unsigned integral type.

3 返回值

realloc()函数的返回值类型为void*型:

  1. 分配成功,返回指向重新分配的内存块的指针;
  2. 分配失败,返回NULL。

cstdlib库描述如下:

1. A pointer to the reallocated memory block, which may be either the same as ptr or a new location.
2. The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
3. C90 (C++98)C99/C11 (C++11) : A null-pointer indicates either that size was zero (an thus ptr was deallocated), or that the function did not allocate storage (and thus the block pointed by ptr was not modified).

4 示例

示例代码如下所示:

int main() {
   // 初始分配内存
   size_t init_size = 5;
   int* array = (int*)malloc(init_size * sizeof(int));
   // 检查 malloc 是否成功
   if (array == NULL) {
      perror("Failed to allocate memory ");
      exit(1);
   }
   // 初始化内存
   for (size_t i = 0; i < init_size; i++) {
      array[i] = i + 1;
   }
   // 打印数组内容
   printf("扩展前数组大小是 %u,数组元素是 ", init_size);
   for (size_t i = 0; i < init_size; i++) {
      printf("%d ", array[i]);
   }
   printf("\n");
   // 扩展内存
   size_t new_size = 10;
   int* temp = realloc(array, new_size * sizeof(int));
   // 检查 realloc 是否成功
   if (temp == NULL) {
      perror("Failed to reallocate memory ");
      free(array);  // 释放原来的内存
      exit(1);
   }
   
   array = temp;  // 更新指针
   // 初始化新分配的内存
   for (size_t i = init_size; i < new_size; i++) {
      array[i] = i + 1;
   }
   // 打印数组内容
   printf("扩展后数组大小是%u,数组元素是 ", new_size);
   for (size_t i = 0; i < new_size; i++) {
      printf("%d ", array[i]);
   }
   printf("\n");
      // 释放内存
   free(array);
   //
   return 0;
}

代码运行结果如下图所示:

在这里插入图片描述

标签:函数,realloc,34,内存,new,ptr,block,size
From: https://blog.csdn.net/XDUryan/article/details/141107137

相关文章

  • 034.Vue3入门,插槽Slot中同时显示主页面和插槽页面的内容
    1、App.vue代码:<template><div><h3>主页面</h3><Slot001v-slot="slotProps"><h4>{{msg}}==={{slotProps.msg}}</h4></Slot001></div></template><script>i......
  • C++虚函数表、地址详解(x86/x64)
    参考博文:c++虚函数表、地址详解-CSDN博客本文在上述博文的基础上,补充了x64下的验证代码。一.什么是虚函数表,它有什么特点?        虚函数大家都知道是基本用于实现多态的,当父类指针指向子类对象的时候,如何确定调用的函数是父类里的还是子类里面的,这就要用到虚函数表......
  • JS【详解】数据类型检测(含获取任意数据的数据类型的函数封装、typeof、检测是否为 nul
    【函数封装】获取任意数据的数据类型/***获取任意数据的数据类型**@paramx变量*@returns返回变量的类型名称(小写字母)*/functiongetType(x){//获取目标数据的私有属性[[Class]]的值constoriginType=Object.prototype.toString.call(x);//......
  • 多项式与生成函数
    多项式与生成函数1普通生成函数1.1定义\(F(x)=\sum_{n\geq0}a_nx^n\)。例如:序列\(<1,2,3>\)的生成函数为\(1+2x+3x^2\);序列\(<1,2,4,\dots>\)的生成函数为\(\sum_{n\geq}2^nx^n\)。1.2加减运算\(F(x)\pmG(x)=\sum_{n\geq0}(a_n+b_n)x^n\)。即\(F(x)\pmG(x)......
  • 21:Python函数全局变量和局部变量
    #全局变量与局部变量,全局变量大写,局部变量小写NAME='ladfs'#定义全局变量,全局作用域顶格defchange_name():print('change_name',NAME)#调用全局变量change_name()#全局变量与局部变量NAME='ladfs'#定义全局变量defchange_name():......
  • Linux文件操作函数仿写cat命令,diff命令,cp命令
    #include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<fcntl.h>#include<unistd.h>#include<string.h>intmain(intargc,constchar*argv[]){ printf("参数个数=%d\n",argc); if(2>argc) ......
  • 【C++学习笔记 16】构造函数初始化列表
    当编写类并向其中添加成员时,通常需要某种方式对这些成员进行初始化。常见的方法,如写一个构造函数赋初值classEntity{private: std::stringm_Name;public: Entity(){ m_Name="UnKnow"; } Entity(conststd::string&name){ m_Name=name; } constst......
  • MySQL:复杂查询 (一)——聚合函数&分组查询&联合查询
    目录1、聚合查询1.1聚合函数1.1.1COUNT()1.1.2SUM()1.1.3AVG()1.1.4MAX(),MIN()1.2分组查询1.2.1GROUPBY子句 1.2.1.1round()1.2.2HAVING1.2.3 示例2、联合查询2.1①取相关表笛卡尔积 2.2②过滤无效数据2.3③精简查询结果2.3.1表的别名3、综......
  • Linux5:Shell编程——函数、重定向
    目录前言一、函数1.函数结构2.函数实例3.函数传参二、重定向1.输出重定向2.输入重定向3.同时使用4.重定向深入了解 5.垃圾桶总结前言    Shell编程将会在本章完结 一、函数1.函数结构#!/bin/sh#函数functionfun1(){echo"thisisaf......
  • 枚举、typedef、位运算、堆内存-malloc 函数
    目录枚举定义枚举值枚举类型枚举的优点枚举的注意事项示例程序总结typedef基本用法复杂数据类型的重命名位运算位移操作总结堆内存malloc 函数free 函数常见问题枚举定义在C语言中,枚举(enum)是一种数据类型,它允许定义一组具名的常量。使用枚举可以使代码......