I\'m trying to build a dynamically grown array of strings. Neither the number of strings nor the length of each string is known at compile time. Here\'s the code I came up w
The following statement makes both result[0]
and temp
point to the same memory address:
result[0]=temp;
Having performed the above assignment, you then free(temp)
and try to access result[0]
:
free(temp);
printf ("%s \n", result[0]);
This is undefined behaviour, since you're accessing the memory that's just been deallocated.
The same goes for the identical code you have for result[1]
.
freeing
itstrcat
ing to unallocated memory (plus the uneducated realloc(result[0]
makes no sense)You could try this:
char **result = NULL;
result = realloc(result, sizeof(char *) * 1);
result[0] = strdup("hello");
/* ... */
result = realloc(result, sizeof(char *) * 2);
result[1] = strdup(" world");
Now strdup
isn't standard but it's not hard to steal it / fake it. Here's one attempt:
char *strdup2(const char *str)
{
size_t len;
char *rval = NULL;
len = strlen(str); /* We should probably check this. */
rval = malloc(len + 1); /* And this. */
memcpy(rval, str, len);
rval[len] = 0;
return rval;
}
I was under the (possibly wrong) impression you want to later modify the strings. If that is not the case, simply storing them (without strdup
) is adequate:
result[0] = "hello";