I have a function in C that dynamically allocates a buffer that is passed to another function to store the return value. Something like the following dummy example:
void other_function(float in, float *out, int out_len) { } void function(float *data, int data_len, float *out) { float *buf; int buf_len = 2 * data_len, i; buf = malloc(sizeof(float) * buf_len); for (i = 0; i < data_len; i++, data++, out++) { other_function(*data, buf, buf_len); } free buf; }
function is called by an iterator over a multidimensional array (this, of course, is the core of NumPy gufunc), so it is called millions of times with the same value for data_len . It seems wasteful to create and destroy a buffer over and over again. Usually I move the buffer allocation to the function that calls the function and pass it a pointer, but I do not control it directly, so this is not possible. Instead, I plan to do the following:
void function(float *data, int data_len, float *out) { static float *buf = NULL; static int buf_len = 0; int i; if (buf_len != 2 * data_len) { buf_len = 2 * data_len; buf = realloc(buf, sizeof(float) * buf_len); } for (i = 0; i < data_len; i++, data++, out++) { other_function(*data, buf, buf_len); } }
This means that I never directly free the memory that I allocate: it is used again in subsequent calls, and then lingers there until the exit of my program. This is not like what needs to be done, but not so bad as the amount of allocated memory will always be small. I'm worry? Is there a better approach to this?
Jaime source share