Dynamicly resize array of strings
I've made a simple demo (see below) that calls a function which adds some strings to an array. What I don't understand is why if I comment the malloc statements in the addSomeStrings function, everything still works ok. Is this just by chance or are those statements not needed?
I ask because I have something similar in an application I am developing which works fine without the malloc statements but with them it throws a segmentation fault when i try and display the strings in the array (output of strtok function).
Any help would be most appreciated.
Code:
void addSomeStrings(char **data)
{
printf("Allocating heap space\n");
data[0] = (char *) malloc(5*sizeof(char *));
data[0] = "first";
printf("Reallocating heap space\n");
data = (char **) realloc(data, 2 * sizeof(char *));
data[1] = (char *) malloc(6*sizeof(char *));
data[1] = "second";
printf("Reallocating heap space\n");
data = (char **) realloc(data, 3 * sizeof(char *));
data[2] = (char *) malloc(5*sizeof(char *));
data[2] = "third";
}
int main()
{
char **data;
int i=0;
data = (char **)malloc(sizeof(char *));
addSomeStrings(data);
for (i=0; i<3; i++)
{
printf("String %s\n", data[i]);
}
return 0;
}