BUSY
BUSY

Reputation: 180

How to optimize malloc() or dynamically fill memory of an unknown size?

I'm just playing around in C, and I wanted a function that would generate the Fibonacci Sequence up to a variable maximum term and be returned as a pointer to an array. The code below works just fine.

But my question is actually whether it can be optimized at all? I'm generating the same fibonacci sequence twice; first to find how many fibterms there are up to the maxterm and allocate enough memory to fit all the terms, and a second time to fill that memory with the terms I've now found twice.

Am I overlooking something more key to malloc() or is there a way to combine these two loops? Can I continually be calling malloc and copying the old fib into a new one? Is that bad to be repeatedly calling for new memory?

int* genFib(int maxterm) 
{   
    // generate a way for x to be the fibonacci term
    // with y being the previous term
    int x = 1, y = 1;

    // fibterms is a global variable that counts the
    // number of terms, to create the right size array.
    // it needed to be global to find the size elsewhere
    do
    {
        int temp = x;
        x += y;
        y = temp;
        fibterms++;
    }
    while (x < maxterm);

    // the array has enough space allocated now, but
    // is empty for the moment.
    int* fib = malloc(sizeof(int) * fibterms);   

    // i need to now redo my previous loop just to
    // fill the array with the correct terms, so all
    // counters and terms are reset.
    x = 1, y = 1;
    fibterms = 0;

    // same loop as above, but 
    // filling the array this time
    do
    {
        fib[fibterms] = x;
        int temp = x;
        x += y;
        y = temp;
        fibterms++;
    }
    while (x < maxterm);
    return fib;
}

Upvotes: 1

Views: 769

Answers (1)

Nibnat
Nibnat

Reputation: 119

int* fib = malloc(sizeof(int));   
    x = 1, y = 1;
    fibterms = 0;

    // same loop as above, but 
    // filling the array this time
    do
    {
        fib[fibterms] = x;
        int temp = x;
        x += y;
        y = temp;
        fibterms++;
        fib = (int *)realloc(fib , sizeof(int)*(fibterms+1));//fibterms is a int from 0
    }

Upvotes: 1

Related Questions