I am trying to build a dynamically grown array of strings. At compile time, neither the number of lines nor the length of each line is known. Here is the code that I have come up with so far (it's just me playing with the syntax):
char **result = NULL; char *temp = NULL; result = (char **)realloc (result,sizeof(char *) * 1); temp= (char *)realloc(temp,5 * sizeof(char)); strcat(temp,"hello"); temp= (char *)realloc(temp,10 * sizeof(char)); strcat(temp," world"); printf ("%s \n", temp); result[0]=temp; free(temp); printf ("%s \n", result[0]); result = (char **)realloc (result, sizeof(char *) * 2); temp= (char *)realloc(temp,10 * sizeof(char)); strcat(temp,"0123456789"); temp= (char *)realloc(temp,15 * sizeof(char)); strcat(temp,"asdfg"); printf ("%s \n", temp); result[1]=temp; free(temp); printf ("%s \n", result[0]); printf ("%s \n", result[1]);)
Now, when I print the result [0] or the result [1], its just an empty line, why does not it result [1] = temp; work?
Here is what I tried before, but it didnโt work, I continued to get "wrong size" errors when using realloc () in this last line:
char **result = NULL; result = (char **)realloc (result,sizeof(char *) * 1); result[0]= (char *)realloc(result[0],5 * sizeof(char)); strcat(result[0],"hello"); printf ("%s \n", result[0]); result[0]= (char *)realloc(result[0],10 * sizeof(char)); strcat(result[0]," world"); printf ("%s \n", result[0]); result = (char **)realloc (result, sizeof(char *) * 2); result[1]= (char *)realloc(result[1],10 * sizeof(char)); strcat(result[0],"0123456789"); result[0]= (char *)realloc(result[1],15 * sizeof(char)); strcat(result[0],"asdfg");
If anyone can help me get any version, I would really appreciate it.
UPDATE: Well, I have both versions of the code. Now, when I try to use this format in my real program, I get errors like
*** glibc detected *** ./uvicfmt3: realloc(): invalid next size: 0x08ed3170 ***
Now in my program the "result" is declared as a global variable (using the second version of my code), and the realloc functions are called in different subprograms. Is that what causes the problem? How could I get around this?