The idea is good, but a few more things are needed (or preferred).
Checks
Before malloc()
Before calling malloc
, you should first check if size
is valid (not negative number).
Also, although this shouldn't happen but if in alloc_mem
, *x
has already been allocated a piece of memory, and you assign a new memory to the pointer *x
, it causes memory leak. It means part of your memory is not 'recycled' and is lost. It is very important that your program doesn't cause any memory leak because eventually your system will crash due to insufficient memory and reboot is the only way.
You can (one of the ways) first set the pointer you just declared (*x
in test_function
) to NULL
. Then, in alloc_mem
first check if the passed argument *x
is NULL
or not. If it is not NULL
, you can just return
to test_function
, or free
it and malloc
a new memory to it. (Read the comment of this answer)
After malloc()
After malloc()
, you should check if the returned address (in this case, *x
) is a valid address. If your machine has run out of memory (very rare, but not impossible), you get a NULL
pointer. If you didn't perform the check and continue the insertion / assignment, you will get a Segmentation Fault.
Conventions
Setting the pointer to NULL
after free
ing it
It is a good practice to set the pointer (x
in test_function
) to NULL
after free
ing it. You can get a detailed explanation here. It doesn't do much in your case but when you are working on a bigger project, it saves a lot of time debugging.
Check memory leaks
You can check if your program causes any memory leak by using valgrind. After installed, just use it like
$ gcc prog.c -o prog
$ valgrind ./prog
You should get something like
HEAP SUMMARY:
==4889== in use at exit: 0 bytes in 0 blocks
==4889== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==4889==
==4889== All heap blocks were freed -- no leaks are possible