I am studying some routines from Numerical Recipes and I did not understand the use of the macro #define FREE_ARG char* in the implementations to deallocating memory. Here goes one piece of the code:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#define NR_END 1
#define FREE_ARG char*
float *vector(long nl, long nh)
/* allocate a float vector with subscript range v[nl..nh] */
{
float *v;
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
if (!v) nrerror("allocation failure in vector()");
return v-nl+NR_END;
}
void free_vector(float *v, long nl, long nh)
/* free a float vector allocated with vector() */
{
free((FREE_ARG) (v+nl-NR_END));
\\ ^
\\ '----- why?
}
My question is: Why the memory is being released in this manner free((FREE_ARG) (v+nl-NR_END));?
That is probably a very bad code.note
free()
takes the argument type void *
. Any pointer type can be implicitly converted to a void *
, no cast needed.
Note:
In this line
v=(float *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(float)));
the cast is also not required and should be avoided. See this discussion on why not to cast the return value of malloc()
and family in C
.. This is also one of the reasons behind the usage of bad earlier.