If I want to allocate memory in function:
char* allocate() {
char *cp = (char*)malloc(10);
...
return cp;
}
can I use the returned content in cp
from main()
? and how to free cp
?
If I want to allocate memory in function:
char* allocate() {
char *cp = (char*)malloc(10);
...
return cp;
}
can I use the returned content in cp
from main()
? and how to free cp
?
can I 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
malloc
(and family) in CYou should always test against failure of malloc(3), so at least use perror(3) & exit(3) like:
char *cp = malloc(10);
if (!cp) { perror("malloc"); exit(EXIT_FAILURE); };
Some Linux systems are enabling memory overcommit. This is a dirty feature that you should disable.
If you are coding seriously (e.g. a robust library to be used by others) you may need to provide more sophisticated out-of-memory error recovery (perhaps having a convention that every allocating routine could return NULL
on failure). YMMV.
Indeed, at some later point you need to call free(3) with the pointer in cp
. If you don't you'll have a memory leak. After that you are not allowed to use i.e. dereference that pointer (be careful about pointer aliases) or simply compare it against some other pointer; it would be undefined behavior.
It is important to have a convention about when and who should call free
. You should document that convention. Defining and implementing such conventions is not always easy.
On Linux you have quite useful tools to help about C dynamic memory allocation : valgrind, passing -Wall -Wextra -g
(to get all warnings and debug info) to the GCC compiler, passing -fsanitize=address
to a recent gcc
, etc.
Read also about garbage collection; at least to get some terminology, like reference counting. In some C applications, you might later want to use Boehm's conservative GC.
1. can I use the returned content in cp in main()?
Yes, you can. The scope and lifetime of dynamically allocated memory (on heap) is not limited to the function scope. It remains valid untill it is free()
d.
Note: Always check for the success for malloc()
and do not cast it's return value.
2. and how to free cp?
Once you've done using the memory, from main()
, or from any other function, you can call free(<pointer>);
, where <pointer>
is the variable in which you had collected the return value of allocate()
.