Search code examples
crecursionmallocfree

Can I free mallocs that are being generated in every step of a recursion in C?


I am making a simulation with C (for perfomance) that (currently) uses recursion and mallocs (generated in every step of the recursion). The problem is that I am not being able to free the mallocs anywhere in the code, without having the wrong final output. The code consist of two functions and the main function:

evolution(double initial_energy)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

double * evolution(double initial_energy){
    
    double * energy_vec = malloc(sizeof(double)*50);
    for(int i = 0; i <= 50; i++){

        energy_vec[i] = 0;

    }

    int i = 0;

    while(initial_energy > 1){

        initial_energy /= 2;
        energy_vec[i] = initial_energy;
        i++;
    }
    return energy_vec;
}

here is where mallocs are generated. Then I define recursion(double initial_energy) that return the total number of events, being events the times that the initial_energy is divided by 2 until its value is less than 1.

double recursion(double initial_energy){

    int event_counter = 0;
    int j = 0;
    double * Energy;

    Energy = evolution(initial_energy);

    while(Energy[j] > 0.0){

        event_counter++;
        event_counter += recursion(Energy[j]);
        j++;
    }
    return event_counter;
}

and finally the main function, that here doesn't make much a difference to have it, but for the sake of completeness here it is

int main(){

    int trials = 20000;
    int events;
    double initial_energy = 70;

    for(int i = 0; i <= trials; i++){

        events = recursion(initial_energy);
        printf("%i) events = %i\n",i, events);
        usleep(200);
    }
    return events;
}

So, is it possible for this code, to free the mallocs anywhere and have the correct result at the end? (The correct result should be 2**N - 1, where N is the number of times a value greater than 1 can result from dividing initial_energy by 2 successivelly. For example, for this code, the correct answer would be 127 at the end of the program). I have tried defining the malloc inside the for loop in the main function, and freeing it right after I call recursion, but it doesn't hold the correct result.

I only use C ocassionally (when python performance is too slow for some sort of calculations), so I do not have the technical understanding of the language that I would like. So I am open to whatever changes in the code are necessary.

Thanks in advance!


Solution

  • You're supposed to free memory right after the last time it will be used. In your program, after the while loop in recursion, Energy isn't used again, so you should free it right after that (i.e., right before return event_counter;).