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.
Specifically I have a function that replaces a substring in a string, I return the pointer to the newly malloc
ed memory. Do I free
the original string ?
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? Is it safe to free that memory (assuming it's not used anywhere else)?
Edit: str comes from here:
str = axiom_element_get_text(element, env, messageDataNode);
findAndReplace
is implemented and on whetherstr
was allocated withmalloc
. Pointers have many uses; being handles to allocated memory is just one of them.free
memory that was returned bymalloc
,calloc
orrealloc
. Check whetherstr
fits this condition.