Skip to content

The cost of memory allocation in a loop in C

An answer to this question on Stack Overflow.

Question

Is there a significant difference between allocating an array inside or outside a loop in terms of cost of time?

I use many arrays in functions inside a loop in my program, should I pass all the arrays as function parameters to increase the performance although it decreases the readability? For example:

#include <stdlib.h>
#define N 1000000
void foo()
{
    int* array = (int*)malloc(N*sizeof(int));
    /*
    Do something with the array
    */
    free(array);
}
int main()
{
    int i;
    for(i=0; i<1000000; i++)
        foo();
    return 0;
}

or

#include <stdlib.h>
#define N 1000000
void foo(int* array)
{
    /*
    Do something with the array
    */
}
int main()
{
    int i;
    int* array = (int*)malloc(N*sizeof(int));
    for(i=0; i<1000000; i++)
        foo(array);
    free(array);
    return 0;
}

Answer

Declaring the array and then using it strikes me as the better way to do things.

Your declaration takes place in a higher-level body of code and happens once: therefore it is easy to understand what is going on, change the allocation size, handle allocation errors, and debug.

Declaring the array in the for loop raises a definite code smell for me: it is a solution that lacks modularity.