There is a code:
char * str = strrem("test_string", "s"); str = strrem(str, "_"); printf("%s\n", str);
strrem
:
char * out = calloc(strlen(_str), 1); ... return out;
How can I fix a memory leak by leaving the strrem
function clean.
There is a code:
char * str = strrem("test_string", "s"); str = strrem(str, "_"); printf("%s\n", str);
strrem
:
char * out = calloc(strlen(_str), 1); ... return out;
How can I fix a memory leak by leaving the strrem
function clean.
char * str = strrem("test_string", "s); //Ошибка синтаксиса, не соберется. str = strrem(str, "_");
Given that strrem () allocates memory via calloc () and strrem () is called twice, you must have TWO pointers to store the allocated memory, then to call free () for both.
For example:
char* str = strrem(...); char* ptr1 = str; str = strrem(...); ... //Тут аццкей кодес free(str); //освобождение от первого strrem free(ptr1); //освобождение от второго strrem
I did not understand what exactly strrem()
does with its arguments, but suppose that based on them creates a certain result (string) in dynamic memory, which it returns.
At the same time, you do not want to free memory (call free()
) of the first argument inside strrem()
(perhaps because it is sometimes a constant), you do not want to write "extra" lines of code, but always want to be able to use this entry:
str = strrem(str, arg2);
and avoid memory leaks.
Summarizing the idea in the answer @ Vladimir Martyanov, all this (mainly saving lines) can be implemented something like this:
char *str, *prev = 0; .... str = strrem("xaxa", "xoxo"); ... while (...) { free(prev), prev = 0; // не забудьте обнулять, чтобы потом не упасть от повторного освобождения той же памяти str = strrem(prev = str, "abc"); ... // кстати, тут доступны как старое (в prev), так и новое значения str } ... free(str); free(prev); // поскольку мы обнуляем prev после free(prev), то это безопасно
Those. in those places where you call strrem()
with an argument, the memory of which should then be released, you immediately (at the call point) remember this address.
If you wish (and having before your eyes more different cases of strrem
use), it is advisable to arrange all such calls with release in the form of macros (with a sufficient variety of them, the variable prev
generally able to be removed from sight).
Source: https://ru.stackoverflow.com/questions/561096/
All Articles
str
variable is assigned a new value, I lose access to the old one (there is a leak in this place). If I callfree(str)
before the assignment operation, I will not be able to get the value of the variablestr
. - eanmos pmstr
get a new value? - eanmos