8
linux C语言编程,使用realloc函数后,原内容数据还在吗?原指针还能用吗?原内存被释...
source link: https://blog.popkx.com/linux-c-language-programming-the-use-of-realloc-function-the-original-content-data-is-still-there/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
linux C语言编程,使用realloc函数后,原内容数据还在吗?原指针还能用吗?原内存被释放吗?
在回答题目中的问题之前,先man
一下realloc
函数:
realloc 函数所在头文件
stdlib.h
realloc 函数原型
void *realloc(void *ptr, size_t size);
realloc 函数说明
- 该函数将
ptr
指向的内存大小修改为size
。内存中的数据从开头到size
保留不变。 - 如果
size
大于原内存大小,则多出的部分会被初始化。 - 如果
ptr
是NULL
,此时 realloc 就相当于malloc
函数。 - 如果
ptr
不为NULL
,size=0
,那么 realloc 就相当于free
函数。 - 另外有一点需要注意,如果 ptr 不为 NULL,那么 ptr 必须是之前
malloc
,calloc
,realloc
函数返回的指针,不能任意指定。
realloc 函数返回值
如果成功了,函数返回一个指向新分配的内存的指针,新指针可能不等于原来的指针。如果失败了,则返回 NULL,原来的内存不会被释放。
对于标题中提到的问题,上面已经介绍的比较清楚。根据 realloc 的返回值说明,下面这种使用方法应该避免:
...
void* buf = malloc(len);
...
buf = realloc(buf, size);
...
因为如果 realloc 失败了,buf 会被赋值为 NULL,而原内存还没有被释放,就泄漏了。
下面再给出一个demo例子:
#include <stdio.h>
#include "stdlib.h"
#include "string.h"
int main()
{
char str[] = "blog.popkx.com";
char* buf = (char*)malloc(strlen(str));
if(!buf)
return -1;
strcpy(buf, str);
printf("buf(%p): %s\n", buf, buf);
char* lbuf = (char*)realloc(buf, strlen(str)*2);
if(!lbuf)
return -2;
strcpy(lbuf+strlen(str), str);
printf("lbuf(%p): %s\n", lbuf, lbuf);
free(lbuf);
return 0;
}
编译执行,输出如下:
$ ./a.out
buf(0xae9010): blog.popkx.com
lbuf(0xae9440): blog.popkx.comblog.popkx.com
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK