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 with so far (this is 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 result[0] or result[1], its just an empty string, why doesn't result[1]=temp; work?
Here's what I tried earlier, but it didn't work, I kept getting "invalid size" errors when using realloc() on that 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 anybody could help me get either version working, I would be very grateful.
UPDATE: Ok, I got both versions of the code working. Now when I try to use this same format in my actual program, I get errors such as
*** 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 subroutines. Is that what's causing the problem? How could I get around this?
#include <stdlib.h>and get rid of the casts. If you're compiling with a C++ compiler, try to write C++ in the 1st place ;)realloc(): invalid next size- really, any error from*allocbesides "out of memory" - is a sign. It means you've probably corrupted the heap, overwriting the data structures that*allocuses to keep track of the location and size of free blocks. When you see that error, start looking for invalid array writes, doublefrees, and stuff like that.