Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of strings memory reallocation in C

I have a project to do and I need to reallocate the memory for the array. I tried many times, but I have found just one version that works.

void resize(int* size, char*** arr)
{
    *size *= 2;
    *arr = realloc(*arr, sizeof(char*) * *size);
    nulltest(*arr);    // This checks if the allocation was successful
}
resize(&size, &arr);

This function doubles the capacity of the array, but I think it’s done too complicated, so I want to ask you guys, if this can be simplified or not. I’m open to new solutions too.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. int is not the good type for sizes. Use the correct one size_t
  2. Try to avoid side effects (ie modifying the objects passed by reference) without special need.
  3. Your code is potentially leaking memory. If realloc failes you loose the reference to the previously allocated memory. The integer referenced by size is also changed without the need.

I would implement it this way:

char **resize(char **arr, size_t newsize)
{
    return realloc(arr, size * sizeof(*arr));
}

And the caller function should check for the errors.

But what is the point of defining this function? This one only returns the return value of realloc.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading