snoopy snoopy - 2 months ago 7x
C Question

Can calloc ever safely be used without free?

I'm a Java programmer with almost no C/C++ experience trying to adapt some simple C/C++ code used with the JNI.

I read that an array (or any other memory chunk) allocated with single calloc() should always be deallocated with single free() call with SAME pointer as returned by malloc. It causes a memory leak if it's not free'd.

The C/C++ code I'm adapting uses calloc(), but has no corresponding free() call. Are there any situations where it shouldn't have a free() call, or is the code badly written?


A calloc(...) or malloc(...) should always be accompanied by a corresponding free() so that the application/OS can reclaim the memory for other purposes. An application that doesn't free memory "leaks" that memory and renders it unusable.

If you do not use free(), a sensible operating system will make that memory available again when the application closes, but a program that relies on the OS to clean up any memory leaks is badly programmed and should be fixed.

This (as you already know) is unlike Java, which has a garbage collector to periodically clean up any memory that is not used anymore.

As a general additional note, it is not required to use the same pointer to free memory. For example, you could do this:

// Create an array of 10 integers.
int *x;
x = calloc(10, sizeof(int));

// Create another pointer 'y', which uses the same array as x.
int *y;
y = x;

// Delete the array. Both 'x' and 'y' are unusable now.