dissem dissem - 3 months ago 26
C Question

Adding string to array, pointer being realloc'd was not allocated

I am trying implement a method that adds a given string to an array that ends with a NULL pointer. This is what I have so far but I am getting an error saying that the pointer being realloc'd was not allocated.

int main(void)
{
char **strings = init_array();

strings = add_string(strings, "one");
strings = add_string(strings, "two");

return 1;
}


char **init_array(void)
{
char **array = malloc(sizeof(char *));
array[0] = NULL;
return array;
}


char **add_string(char **array, const char *string)
{
unsigned int size = 0;
while (*array) {
size++;
array++;
}

char **newarr = (char **)realloc(array, sizeof(char *) * (size + 2));

newarr[size] = malloc(strlen(string)+1);
strcpy(newarr[size], string);
newarr[size+1] = NULL;

return newarr;
}

Answer

The issue is array++. You have to pass realloc the same value malloc returned (your array argument), but you modify it during the loop, so it'll work only the first time (because *array will immediately false). You could use:

size_t size;
for(size = 0; array[size]; size++);

And leave the rest untouched.