Search code examples
cmallocrealloc

How to realloc() in the middle of an array?


I have an array of pointers

    char *wordlist[9];

and then I malloc() a block of memory on every of this pointers

for(int i=0; i<9; i++)
    wordList[i] = (char*)malloc(someLength);

Lets suppose that every time the someLength is different.

And the problem is now, that I want to realloc() ie. 4th elemet of wordList to a larger size than it is now.

wordList[3] = (char*) realloc(&wordList[3], someBiggerSize);

Since malloc allocates a consistent block of memory, is that operation even possible without colliding with wordList[4]?


Solution

  • There's nothing to worry about this in principle. You just have an array of pointers and each element of the array points to a distinct memory block. Each element of the array, each pointer, can be therefore be reallocated independent of the other elements.

    Now, I say in principle because your code does have an error. You should pass wordList[3] rather than &wordList[3] to the realloc.