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?

modsoussi
  • 137
  • 11
  • 2
    What leads you to believe that it is `realloc` that is failing (rather than something else)? What symptom are you seeing? – psmears Jan 26 '15 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. – modsoussi Jan 26 '15 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...) – psmears Jan 26 '15 at 22:20
  • Try to be more specific than "fails to add more integers to the array" - how do you know? Does it crash? Do you get an error message? If so, what is it? These details are important :) – psmears Jan 26 '15 at 22:21
  • The program stops working and windows tells me it's trying to find a solution to an error. But what you just mentioned solved the problem though! I guess I was trying to write off of the end of the array, which was causing the error. – modsoussi Jan 26 '15 at 22:23
  • 2
    @modsoussi it should be `if (i == size)`. Greater-than should never become a possibility or you're already invoking *undefined behavior*. – WhozCraig Jan 26 '15 at 22:24
  • 3
    As an aside, [Don't cast the result of malloc (and friends)](http://stackoverflow.com/q/605845). Also, you should get into the habit of checking for failure to allocate, parse, open files and connections, whatever. – Deduplicator Jan 26 '15 at 22:25
  • @WhozCraig: In what way does `==` succeed where `>=` fails? In this situation they are effectively equivalent, no? – psmears Jan 26 '15 at 22:34
  • @WhozCraig "should be `if (i == size)`", now that is an interesting thought. Any place you know of that has discussed it? Do not want to start a holy war here, but would like to here the pro/con of it. – chux - Reinstate Monica Jan 26 '15 at 23:27
  • @modsoussi Who or what text suggested casting the the return value of `malloc()`? – chux - Reinstate Monica Jan 26 '15 at 23:29
  • @chux: The code in the question casts the return value of both `malloc()` and `realloc()`; that's what brought the topic up. – psmears Jan 26 '15 at 23:56
  • @chux Not where `==` is true and `>=` is not. My point was the `>=` instruction will be different (a `jne` vs `jl`), and to *no benefit*. Given the Op's code the only way greater-than could come into play means the prior accessors have already invoked UB and it starts raining cats. Covering all bases by a blanket open-end range that should never happen in the first place may not make a difference to working code, but the *reader* of the code may well believe `i` *may become greater*, which by all accounts simply cannot happen and stay in the realm of defined behavior. – WhozCraig Jan 27 '15 at 00:19
  • @psmears My interest was why OP originally casts `malloc()` results. – chux - Reinstate Monica Jan 27 '15 at 00:33
  • @chux: This seems to be a very common anti-pattern - it's all over the place in C I come across online... – psmears Jan 27 '15 at 10:24
  • @psmears Still hoping to find _from OP_ why OP did it - that is why my first comment was addressed directly to OP. With your 2 comments, doubt it will now get answered from OP. – chux - Reinstate Monica Jan 27 '15 at 15:14
  • @chux The only reason I did it is because I saw it online, but it was indeed useless. – modsoussi Jan 27 '15 at 19:24

1 Answers1

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 :)

Lamaseed
  • 136
  • 5