I have to write a function that adds the given string to array of strings.
char **add_string(char **array, const char *string)
{
array = realloc(array, (sizeof(string)) * sizeof(char *));
int i = 0;
while (array[i] != NULL){
i++;
}
array[i] = malloc((strlen(string) + 1));
strcpy(array[i], string);
array[i + 1] = NULL;
return array;
}
At the moment I get memory leaks according to Valgrid. I didn't use malloc correctly, but I can't figure out how to fix it. I would really appreciate your help.
sizeofon a pointer gives you the size of the pointer and not what its pointing to, so what you are doing in therealloccall is reallysizeof(char *) * sizeof(char *), which is probably not what you want.reallocwhen you run out of space, not as a tool to create 1-more on each iteration. In the allocation scheme you generally start with some number of pointers that should be sufficient for your needs. (e.g.32, 64, 128, 256, ...) Even with256 pointers, that only takes a tiny2kof memory. Create a convenient#define MAXS 256at the top of your code. You allocate yourchar **array = calloc (MAXS, sizeof *array);You then allocate eacharray[i](or just assign withstrdup). When(i == MAXS), youreallocMAXS * 2 * sizeof *array.