Search code examples
carraysmallocrealloc

Realloc index of array


Having an array as:

type **a;

a[0][data_0]
a[1][data_1]
a[2][data_2]
a[n][data_n]

When extending such an array by doing:

  1. realloc() on a to sizeof(type*) * (n + 1).
  2. malloc() (*a[n]) to fit data_n where data_n is of variable size.

Could there be some issue with realloc() of a?

As in a[2] would always point to data_2, even if a gets moved in memory, or could that link be lost?

As I understand it I end up with something like this in memory:

         Address               Address
a[0] => 0x###131, (*a[0]) => 0x####784
a[1] => 0x###135, (*a[1]) => 0x####793
a[2] => 0x###139, (*a[2]) => 0x####814

After realloc() I could end up with something like:

         Address               Address
a[0] => 0x###216, (*a[0]) => 0x####784
a[1] => 0x###21a, (*a[1]) => 0x####793
a[2] => 0x###21e, (*a[2]) => 0x####814
a[n] => 0x###zzz, (*a[n]) => 0x####yyy

Is this correct? The data_n segments are left alone, or could they also get moved?


Solution

  • Is this correct? The data_n segments are left alone, or could they also get moved?

    Yes, the values of a[i], for 0 <= i < n are copied to the new location, so the pointers point to the same data_i and those will not be moved.

    Could there be some issue with realloc() of a?

    Of course, a realloc can always fail and return NULL, so you should never do

    a = realloc(a, new_size);
    

    but use a temporary variable to store the return value of realloc.