[英]Do I have to use malloc every time I return a pointer
I'm working on a program that has few undiscovered memory leaks. 我正在开发一个几乎没有发现内存泄漏的程序。 The code is literally decades old and written by an unknown person. 该代码实际上已有数十年历史,由不知名的人编写。 I have functions that return char *
and I was wondering if I need to free
the memory. 我有返回char *
函数,我想知道是否需要free
内存。
Specifically I have a function that replaces a substring in a string, I return the pointer to the newly malloc
ed memory. 具体来说,我有一个字符串替换的子功能,我将返回指向新malloc
版内存。 Do I free
the original string ? 我可以free
原始字符串吗?
Original version: 原始版本:
return(findAndReplace(str, "•",rstring));
New version: 新版本:
char *result = findAndReplace(str, "•", rstring);
free(str);
return result;
Questions being: Can I be 100% sure that since I had a pointer returned from somewhere else that memory has been allocated? 问题是:我可以100%确定自从其他地方返回的指针以来已分配内存吗? Is it safe to free that memory (assuming it's not used anywhere else)? 释放该内存是否安全(假设未在其他任何地方使用它)?
Edit: str comes from here: 编辑:str来自这里:
str = axiom_element_get_text(element, env, messageDataNode);
No. You need clearly-defined contracts for your functions' pre and post conditions. 否。您需要为职能的前后条件明确定义合同。 In your "old version", the contract seems to be that the caller provides a pointer str
to an arbitrary string; 在您的“旧版本”中,合同似乎是调用者提供了指向任意字符串的指针str
; storage and lifetime of this string are up to the caller. 此字符串的存储和生存期取决于调用方。 In the "new version", you've changed it so that the caller must provide a pointer to a string obtained by malloc
, and so that the pointer is no longer valid (the object has been freed) after your function returns. 在“新版本”中,您已对其进行了更改,以便调用者必须提供指向malloc
获得的字符串的指针,并且使该指针在函数返回后不再有效(对象已被释放)。
Your core problem is most likely lack of any documentation of the contracts in the existing codebase , meaning you have to reverse-engineer the original author's intents. 您的核心问题很可能是现有代码库中缺少合同的任何文档 ,这意味着您必须对原始作者的意图进行反向工程。 But you shouldn't go trying to change any of thus until you've documented the current situation, decided if a change makes sense, and ensured that you can safely change every point in the existing code that was assuming the original undocumented contracts. 但是,在记录了当前情况,确定更改是否有意义并确保可以安全地更改现有代码中假定原始未记录合同的每个点之前,您不应该尝试进行任何更改。
No, it is not safe the free
memory that was not allocated by malloc
in the first place. 不,首先由malloc
分配的free
内存并不安全。 You can use pointers without malloc/free but in a non-trivial program you are likely to be using malloc and free at certain, but not all, places. 您可以使用不带malloc / free的指针,但是在非平凡的程序中,您可能在某些(但不是全部)位置使用malloc和free。
If you are trying to detect memory leaks in your program, a tool like valgrind might help. 如果您尝试检测程序中的内存泄漏,则可能需要使用valgrind之类的工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.