I allocate memory in function and return char *, how to free it?
Is it possible to use the returned content in cp in main ()?
Yes, you can.
and how to free cp?
Using
free(cp); // Replace cp with the name of the pointer if you are using it in another function
Also, you shouldn't cast the result
malloc
(and families) in C
source to share
You should always check malloc (3) for failure , so use perror (3) and exit (3) like:
char *cp = malloc(10);
if (!cp) { perror("malloc"); exit(EXIT_FAILURE); };
Some Linux systems allow memory recompilation . This is a dirty feature that you should disable.
If you are serious about coding (like a robust library that others should use), you may need more sophisticated out-of-memory error recovery (perhaps with the proviso that each allocator can return NULL
on error), YMMV.
Indeed, at some later point, you need to call free (3) with a pointer in cp
. If you don't, you will have a memory leak . After that, you are not allowed to use, i.e. Dereference this pointer (be careful with pointer aliases ), or just compare it with another pointer; this will be undefined behavior .
It is important to have an agreement on when and to whom to call free
. You must document this agreement. Defining and implementing such agreements is not always easy.
On Linux you have some pretty useful tools to help C dynamically allocate memory : valgrind by passing -Wall -Wextra -g
(to get all warnings and debugging information) to the GCC compiler , passing -fsanitize=address
until recently gcc
, etc.
Read also about garbage collection ; at least get some terminology like reference counting . In some C applications, you might want to use Boehm's conservative GC .
source to share
1.can I use the returned content in cp in main ()?
Yes, you can. The amount and lifetime of dynamically allocated memory (on the heap) is not limited by the scope of functions. It remains in effect until free()
d.
Note. Always test for success malloc()
and do not discard its return value.
2. and how to free cp?
Once you are done using memory, from main()
or from any other function, you can call free(<pointer>);
where <pointer>
is the variable in which you collected the return value allocate()
.
source to share