1

I have some problems using realloc(), so I made a sample program to illustrate the problem using as less code as possible.

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

int main(void)
{
    unsigned int i;
    unsigned long long *a;
    srand(time(NULL));
    a = malloc(sizeof(unsigned long long));
    for (i = 0; i < 20; ++i)
    {
        a[i] = rand() % 32;
        printf("%llu\n", a[i]);
        a = realloc(a, (i + 1) * sizeof(unsigned long long));
    }
    return 0;
}

This outputs:

* glibc detected demo: realloc(): invalid next size: 0x0000000000dc3010 **

Why does this crash?

Edit: I tried chaning (i + 1) to (i + 2) and then the program worked, but I do not understand why. I only request to extend the memory space by one unsigned long long.

3
  • are you not getting any compilation error ? Commented Jul 29, 2013 at 9:18
  • No. This is a runtime message. Commented Jul 29, 2013 at 9:19
  • It has to access an array outside the secured. Commented Jul 29, 2013 at 9:25

2 Answers 2

12

The first time your loop runs, i is equal to 0. You realloc a to hold i + 1 elements, which is... 1 ! The second time your loop runs, you try to write to a[i] with i == 1, which is the second element of your array. But since your array can only hold 1 element, that can cause a crash.

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

2 Comments

very good Nbr! its due to buffer overflow but because of relloc() function correct?
Yes, but only because the reallocation itself is too small. As another answerer mentioned, it should be i + 2 to hold one more element than the current amount.
0

You are allocating location i but accessing location i+1

And do not forget to free the allocated memory before exiting

free(a);

So do this modification to make this code work

a = realloc(a, (i + 2) * sizeof(unsigned long long)); // ERROR HERE

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

    int main(void)
    {
        unsigned int i;
        unsigned long long *a;
        srand(time(NULL));
        a = malloc(sizeof(unsigned long long));
        for (i = 0; i < 20; ++i)
        {
            a[i] = rand() % 32;
            printf("%llu\n", a[i]);
            a = realloc(a, (i + 1) * sizeof(unsigned long long)); // ERROR HERE
        }
        return 0;
    }

1 Comment

Oh, yes forgot to mention: I tried that and then it worked, but I do not understand why. Will update post in a sec.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.