我怎么知道何时应该释放库函数返回的C语言中的字符串? [英] How do I know when I ought to free strings in C returned by library functions?

查看:184
本文介绍了我怎么知道何时应该释放库函数返回的C语言中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用free()¹在我自己的C语言中释放哪些字符串?

我的知识水平:

  • char a[256];:否
  • char *a = "abcdefg";:否
  • char *a = malloc(15L);:是
  • getenv()返回的字符串:
  • Windows函数返回的
  • 字符串²:???

¹或 /GlobalFree()/VirtualFree()
²特别是通过 GetCommandLineW()

解决方案

在文档中,对于您使用的返回字符串(或大于单个简单值(例如整数)的其他数据)的任何API,总会提到它. /p>

是的,这意味着您必须彻底阅读所有此类API函数的文档,以便跟踪并且不会泄漏内存.

Which strings ought I to free in C on my own, using free()¹?

My state of knowledge:

  • char a[256];: no
  • char *a = "abcdefg";: no
  • char *a = malloc(15L);: yes
  • a string returned by getenv(): no
  • strings returned by Windows functions²: ???

¹ or LocalFree()/GlobalFree()/VirtualFree()
² in particular by GetCommandLineW()

解决方案

This will always be mentioned in the documentation for any API you use that returns strings (or other data larger than a single simple value such as an integer).

Yes, this means you have to read the documentation thoroughly for all such API functions, in order to keep track and not leak memory.

这篇关于我怎么知道何时应该释放库函数返回的C语言中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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