0

I'm currently developing a fibonacci for a project, I've had some trouble when managing memory. During the implementation I execute a iterative structure with for and recursive by rfib function. Appears to be a problem with memory even though printing process it's okey. The error shown after modifications is: inferior 1 (process 8076) exited normally

void rfib(int *fib, int x, int last);
int main (int argc, char *argv[]) {
    int N,x;
    int *s = NULL; 
    char *str, *str2;

    if(argv[1] == NULL) {
        exit(1);
    }

    N = atoi(argv[1]);

    s = malloc(sizeof(int)*N);
    str = malloc(sizeof(char)*N);
    str2 = malloc(sizeof(char)*N);  

    if (s==NULL) {
        exit(1);
    }

    s[0]=0;
    s[1]=1;

    // Calculate Fibonacci Serie.
    for (x=2;x<N;x++) { 
        s[x] = s[x-2] + s[x-1];  
    }
    // Print Fibonacci Serie.
    str2 = "Iterative Fibonacci Calculation";
    for (x=0;x<N;x++) {
        sprintf(str,"%s %d: %d\n",str2, x, s[x]);
        write(1,str,strlen(str));
    }

    rfib(s,0,N);

    //Print Fibonacci Serie.
    str2 = "Recursive Fibonacci calculation";
    for (x=0;x<N;x++) {
        sprintf(str,"%s %d: %d\n", str2, x, s[x]);  
        write(1,str,strlen(str));
    }

    str2 = NULL;
    str = NULL;
    s = NULL;
    free(str2);
    free(str);
    free(s);    
    exit(0);
}


void rfib(int *fib, int x, int last) {
    if (x == 0) {
        fib[0] = 0;
    } else if (x == 1) {
        fib[1] = 1;
    } else if (x > 1) {
        fib[x] = fib[x-1] + fib[x-2];
    }

    if (x != last) {
        rfib(fib,x + 1,last);
    }
}
Saxtheowl
  • 4,136
  • 5
  • 23
  • 32
Mpr
  • 1
  • 2
  • You `s = malloc(sizeof(int)*N);` already allocated space for `N` ints ... but, in a loop, you try to `s = (int *) realloc(s, (x + 1) * sizeof(int));` change that into a space of 3, 4, ..., N ints – pmg Oct 25 '19 at 14:34
  • 1
    An array (or malloc'd memory) with `N` elements has valid indexes from `0` to `N-1`. You attempt to access `array[N]` in your recursive function – pmg Oct 25 '19 at 14:37
  • thanks for your comment I've made some changes, however appears an error: inferior 1 (process 8076) exited normally – Mpr Oct 25 '19 at 14:47
  • But "inferior 1 (process 8076) ***exited normally***" (emphasize by me) is not an **error** message, it's a **success** message. What is your problem actually? And, please [edit] your question to show the changes. Please do it by adding the new source so we can see also the old source . – the busybee Oct 25 '19 at 18:31

0 Answers0