Possible Duplicate:
Dynamically grown array of strings
I have a program that needs to return a list of strings. Neither the number of strings nor the length or strings is known at compile time.
Moreover, each string "grows" over a few iterations before the next string is created: I use realloc() and strcat() to add words to each string. There are several subroutines that can either add a string to the array of strings, or expand the strings.
My program is way too large to paste here, so here's a small sample just to demonstrate how I do it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **result = NULL;
void function_1();
void function_2();
int main ()
{
result = (char **)realloc (result,sizeof(char *) * 1);
result[0]= (char *)realloc(result[0],5 * sizeof(char));
strcat(result[0],"hello");
result[0]= (char *)realloc(result[0],10 * sizeof(char));
strcat(result[0]," world");
result = (char **)realloc (result, sizeof(char *) * 2);
function_1();
printf ("%s \n", result[0]);
printf ("%s \n", result[1]);
return 0;
}
void function_1(){
function_2();
result[1]= (char *)realloc(result[1],20 * sizeof(char));
strcat(result[1],"12345");
}
void function_2(){
result[1]= (char *)realloc(result[1],10 * sizeof(char));
strcat(result[1],"0123456789");
result[1]= (char *)realloc(result[1],15 * sizeof(char));
strcat(result[1],"asdfg");
}
so basically, every time I want to create a new string I use
result = (char **)realloc (result,sizeof(char *) * TOTAL_NUMBER_OF_STRINGS);
and every time I want to expand a string I use
result[STRING_NUMBER]= (char *)realloc(result[0],sizeof(char) * (current_length_of_string + length_of_new_word));
The small section of code I've provided works fine, but in my program when I'm using the same approach, eventually I get either something like:
*** glibc detected *** ./uvicfmt3: realloc(): invalid next size: 0x081d1170 ***
or a segmentation fault.
Could someone suggest what's wrong with my approach? I've rewritten the part of my program that deals with dynamic memory allocation several times from scratch, but the problem still persist.
PS Here's my whole program: http://pastebin.com/7WhehW18 The format_file function get's called from the outside.
malloc()etc. in C. It does nothing but obscure diagnostics. Also,"hello"requires six bytes.