0

Say you malloc enough memory space to hold an array of size 20. The program is running and now I need enough memory for an array of size say 40. I tried to do this using realloc but it doesn't seem to be working. My code is the following(I'm trying to find the sum of all even-valued fibonacci terms below 4million):

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

int main(int argc, char** argv){
    int i,sum,size;
    int *fibo;

    size = 20; //initial size of array
    fibo = (int *) malloc(size*sizeof(int));
    fibo[0]=1;
    fibo[1]=1;
    i=2;
    sum=0;

    while(fibo[i-1]<4000000){
            fibo[i] = fibo[i-1]+fibo[i-2];
            printf("fibo[%d] = %d\n", i, fibo[i]);
            if(fibo[i]%2 == 0){
                    sum+= fibo[i];
            }
            i++;
            if(i>size){
                    fibo = (int *) realloc(fibo, (size *= 2)*sizeof(int));
            }
    }

    printf("Sum = %d\n", sum);
    return 0;

}

Anyone know why realloc is failing, and how I can fix it?

16
  • 2
    What leads you to believe that it is realloc that is failing (rather than something else)? What symptom are you seeing? Commented Jan 26, 2015 at 22:18
  • I know I'm going to reach about 23 fibonacci terms before I go over 4 million. Sof if I allocate accordingly in the beginning, the proIgram works fine. When I use realloc, it reaches 20 and fails to add any more integers to the fibo array. ie program stops working. Commented Jan 26, 2015 at 22:20
  • 1
    (NB you probably want "if (i >= size)" rather than "if (i > size)" - otherwise when you do the realloc you've just written off the end of the array...) Commented Jan 26, 2015 at 22:20
  • 2
    @modsoussi it should be if (i == size). Greater-than should never become a possibility or you're already invoking undefined behavior. Commented Jan 26, 2015 at 22:24
  • 3
    As an aside, Don't cast the result of malloc (and friends). Also, you should get into the habit of checking for failure to allocate, parse, open files and connections, whatever. Commented Jan 26, 2015 at 22:25

1 Answer 1

2

During the last iteration, i equals 20 but the expression

if(i>size)

is false, so you do not actually use realloc, then by writing to

fibo[20]

the program is accessing part of the memory that does not belong to it. Changing the expression to

if(i>=size)

should fix it :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.