栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

redis sds 数据结构如何使用 C realloc函数来动态扩容

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

redis sds 数据结构如何使用 C realloc函数来动态扩容

 1 系统函数realloc测试

    mac OS 系统 函数解释

    The realloc() function tries to change the size of the allocation pointed
     to by ptr to size, and returns ptr.  If there is not enough room to
     enlarge the memory allocation pointed to by ptr, realloc() creates a new
     allocation, copies as much of the old data pointed to by ptr as will fit
     to the new allocation, frees the old allocation, and returns a pointer to
     the allocated memory.  If ptr is NULL, realloc() is identical to a call
     to malloc() for size bytes.  If size is zero and ptr is not NULL, a new,
     minimum sized object is allocated and the original object is freed.  When
     extending a region allocated with calloc(3), realloc(3) does not guaran-
     tee that the additional memory is also zero-filled.

#include 

#include 
typedef char *sds;

int main() {
    printf("Hello, World!n");
    char t[] = {'a','b','c','d'};
    sds s = t+1;
    char  bb = s[0];
    char  cc = s[1];
    char  dd = s[2];
    char  flag = *(s - 1);
    printf("%c %c %c %c", flag, bb, cc ,dd);


    int * p=NULL;

    p=(int *)malloc(sizeof(int));

    *p=3;

    printf("np=%pn",p);

    printf("*p=%dn",*p);

    // 空间不变
    p=(int *)realloc(p,sizeof(int));

    printf("p=%pn",p);

    printf("*p=%dn",*p);

    
    // 空间扩大三倍,同时内容会被复制(内存足够的情况下,起始地址不变)
    p=(int *)realloc(p,3*sizeof(int));

    printf("p=%pn",p);

    printf("*p=%d",*p);

    //释放p指向的空间

    realloc(p,0);

    p=NULL;

    return 0;

}
2 结果:

Hello, World!
a b c d

p=0x7fa656405b50
*p=3
p=0x7fa656405b50
*p=3
p=0x7fa656405b50  // 扩容后起始地址没有变化(内存足够)
*p=3
Process finished with exit code 0

3 小结
   函数:void * realloc(void * p,int n);
// 指针p必须为指向堆内存空间的指针,即由malloc函数、calloc函数或realloc函数分配空间的指针。
// realloc函数将指针p指向的内存块的大小改变为n字节。如果n小于或等于p之前指向的空间大小,
// 那么。保持原有状态不变。如果n大于原来p之前指向的空间大小,那么,系统将重新为p从堆上
// 分配一块大小为n的内存空间,同时,将原来指向空间的内容依次复制到新的内存空间上,
// p之前指向的空间被释放。relloc函数分配的空间也是未初始化的。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/352668.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号