Question

I'm trying to copy an array of integers in a dynamically allocated array. At first it has size 1 and with every element I want to increase it's size by one.

Here's the code:

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

int main()
{
    int *nr,i;
    nr=(int *)malloc(1*sizeof(int));
    for(i=1; i<1000; i++)
    {
        nr[i]=i;
        nr=(int *)realloc(nr,i*sizeof(int));

    }

    for(i=1; i<1000; i++)
        printf("%d \n", nr[i]);

    return 0;
}

Thanks!

Was it helpful?

Solution

Here: nr=(int *)malloc(1*sizeof(int));

You are only allocating 4 bytes, yet in your for loop you're then writing 4000 bytes, 3996 of which is in memory not allocated to you. And the realloc you're doing isn't doing anything because you're still only asking for 4 bytes.

Kill the realloc, and just allocate 1000*sizeof(int) at the begining.

Edit for your edit:

Because your loop is from i=1, on the first iteration you're writing in bytes 4-7 instead of 0-3, you need to iterate from i=0. But your realloc is also wrong, because even with your loop you're allocating 1*sizeof(int), which means you'd still be one short. You need to loop from int i=0 and realloc with (i+2)*sizeof(int).

BUT

Don't realloc in a loop, malloc and realloc are very slow. If you did this with a real problem with large numbers you would have a bottleneck here. Allocate once, use it. Even if you can't do it like that, calculate how much space you need in a loop, do a single malloc, then use another loop to fill it in, it will be significantly faster.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top