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.
CodePudding user response:
int
is not the good type for sizes. Use the correct onesize_t
- Try to avoid side effects (ie modifying the objects passed by reference) without special need.
- Your code is potentially leaking memory. If
realloc
failes you loose the reference to the previously allocated memory. The integer referenced bysize
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
.