gpt4 book ai didi

c - asprintf - 何时使用 free()?

转载 作者:太空狗 更新时间:2023-10-29 17:27:22 25 4
gpt4 key购买 nike

asprintf

The functions asprintf() and vasprintf() are analogs of sprintf(3) and vsprintf(3), except that they allocate a string large enough to hold the output including the terminating null byte, and return a pointer to it via the first argument. This pointer should be passed to free(3) to release the allocated storage when it is no longer needed.

这是我的C代码

void function(){
char *out = NULL;
int parts[16] = {1,2,05,003};
asprintf(&out, "%d.%d.%d.%d", parts[0], parts[1], parts[2], parts[3]);
// free(out);
}

int main(void){
function();
return 0;
}

当在 Debug模式下监视函数时,我看到变量在从函数返回时已经被销毁了。为什么我不需要 free() 上面的代码?

你能告诉我在什么情况下我需要免费使用asprintf吗?

顺便说一句,我有“gcc 版本 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)”

enter image description here enter image description here

最佳答案

你需要调用free()

变量离开了作用域,所以变量的实际(free() 需要的地址)在那一点上丢失了,造成了内存泄漏。

free() 函数对先前由 malloc() 或其他堆分配调用返回的内存地址感兴趣,而不是您的特定变量。

你可以这样做:

char *out = NULL, *a, *b, *c, *d, *e;
int parts[16] = {1,2,05,003};
asprintf(&out, "%d.%d.%d.%d", parts[0], parts[1], parts[2], parts[3]);
a = b = c = d = e = out;

这只是另外五个变量,其中包含超出范围的同一地址的副本。当然,堆子系统(通过 malloc()/free() 调用到达)对此一无所知。

关于c - asprintf - 何时使用 free()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17366157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com