How to avoid memory leakage (distribution in the function)
-
There's a clean C task (C 11) to write a prototype function: * voidto_upper(const char *str) The index shall be returned to a copy of the str line where all symbols have been transferred to the top register. I used to do it like,
void *to_upper(const char *str) { void *res = NULL; ssize_t len = strlen(str) + 1; char *str1 = (char*) malloc(sizeof(char) * (len + 1)); for (size_t i = 0; i < len; i++) { if (*(str + i) > 96 && *(str + i) < 123) *(str1 + i) = *(str + i) - 32; else *(str1 + i) = *(str + i); res = (void*) str1; } *(str1 + len) = '\0'; return res; }
But I understand that by dynamizing memory for the new line and without freeing it, I get a leak every time this function is used. Is there any way in which this function is performed to exclude memory loss?
-
Not a serious answer:
Add the following comment:
//Кто забудет вызвать free() для полученного //отсюда указателя будет уволен на месте!
More serious answer:
In the old-fashioned DOOM, the mechanism called https://doom.fandom.com/wiki/Zone_memory ♪ The idea was that memory was dynamically separated from the common pool, and then when the game was moving between levels, and the data were definitely not needed - memory was cleaned up.
You can do the same, point out in the work of the annex at some point when all the lines identified have clearly been overtaken by events and take them down once.