I had a doubt regarding memory management in C , from what I understand I cannot return local memory addresses to a function (in fact this generates a warning in the compiler) but if it is possible, if these addresses of memory were reserved by means of malloc()
(or calloc()
, etc), now from what I know every time we reserve memory we must free it at the end of the program (for this there is free()
) or when we stop using it (since this is not done automatically). Taking all this into account... If I have a function that returns a string
(with dynamically allocated memory of course), let's say for example:
char *nombre();
and I use it like this:
printf("Hola: %s",nombre());
Since when I exit the function I lose the memory address, is it stored without my being able to do anything? Would the most correct thing be to store the memory address returned by the function, print it and then release it?
Thanks in advance.
Effectively; the correct thing is to release all the memory that you do not use.
All standard library functions indicate (if applicable) what is happening with the memory they use.
Some give you control of that memory, being your responsibility to release it; case of, for example,
strdup( )
.Others use an internal buffer , which they reuse every time you call them. You don't have to release it yourself (under penalty of causing errors), but you have to control the use of these functions, so as not to interfere one call with another.
Any memory block that you allocate via
malloc( )
and do n't free will never be freed by the system; It's a common mistake, called memory leak .If you are interested in the subject, you can search for information on allocators : the functions that perform the reservation, reallocation and release of memory blocks. There are many: jemalloc, tlsf, ... more or less suitable for certain uses: speed, compaction, multithread , ...
There are also mechanisms to self -release memory when not in use: memory collectors ; for example, the Boehm-Demers-Weiser, usable from C as libraries.
Finally, there are techniques to simplify the release (in theory), such as reference counting, linked lists of references, ...
Memory management is a whole world .
EDIT
If you just want the function to take care of everything, I can think of several options:
1 - Use a static buffer:
Advantage:
Disadvantages:
2 - Use an internal buffer.
Similar to 1 , you can change the size dynamically, adjusting it as needed on each call.
Advantage:
Disadvantages:
malloc( )
orrealloc( )
that you use.If the use is more complex , you will have to use other solutions: initialization and finalization functions, object orientation, ...