当一个第三方的C函数返回一个指针,你应该自己自由了吗? [英] When a third-party C function returns a pointer, should you free it yourself?

查看:132
本文介绍了当一个第三方的C函数返回一个指针,你应该自己自由了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有返回指针几乎一定新鲜分配的数据的许多功能(特别是在POSIX库)。他们的联机帮助不说,如果你要释放他们,或者如果有在玩一些不起眼的机制(如指针返回到静态缓冲区,或沿着这些路线的东西)。

There are many functions (especially in the POSIX library) that return pointers to almost-necessarily freshly allocated data. Their manpages don't say if you should free them, or if there's some obscure mechanism at play (like returning a pointer to a static buffer, or something along these lines).

例如, INET_NTOA 函数返回一个的char * 最有可能不知从哪里出来,但手册页没有说明它是如何分配的。我结束了使用 inet_ntop ,而不是因为至少我知道在哪里目的地分配来的。

For instance, the inet_ntoa function returns a char* most likely out from nowhere, but the manpage doesn't say how it was allocated. I ended up using inet_ntop instead because at least I knew where the destination allocation came from.

什么是对C函数返回指针的标准规则?谁是负责释放他们的记忆?

What's the standard rule for C functions returning pointers? Who's responsible for freeing their memory?

推荐答案

有真的不是一个标准的规则。有些功能需要你传递一个指针,而他们填写数据转换成空间(例如,的sprintf )。其他人返回一个静态数据区的地址(例如,许多在&LT的功能; time.h中> )。在需要的时候其他的还是分配内存(例如, setvbuf用来)。

There really isn't a standard rule. Some functions require your to pass a pointer in, and they fill data into that space (e.g., sprintf). Others return the address of a static data area (e.g., many of the functions in <time.h>). Others still allocate memory when needed (e.g., setvbuf).

关于你能做的最好是的希望的该文件告诉你的指针有什么需要被释放。通常你不应该试图释放它返回,除非文档告诉你指针。除非你在一个缓冲区的地址传递它的使用,或者指定你需要释放内存,你应该通常认为它使用的是静态数据区。你应该承担的价值,这意味着(除其他事项外)的将会的被任何后续调用相同的常规改变。如果你正在编写多线程code,通常应假设功能的的真正线程安全的 - 你有需要同步共享数据区,所以你应该获得锁,调用功能,数据复制出来的数据区,然后才释放锁。

About the best you can do is hope that the documentation tells you what pointers need to be freed. You shouldn't normally attempt to free pointers it returns unless the documentation tells you to. Unless you're passing in the address of a buffer for it to use, or it specifies that you need to free the memory, you should generally assume that it's using a static data area. This means (among other things) that you should assume the value will be changed by any subsequent calls to the same routine. If you're writing multithreaded code, you should generally assume that the function is not really thread-safe -- that you have a shared data area that requires synchronization, so you should acquire a lock, call the function, copy the data out of its data area, and only then release the lock.

这篇关于当一个第三方的C函数返回一个指针,你应该自己自由了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆