I have a 2d dynamically allocated char array that is supposed to hold strings from a file (stdin) up to a space character. Since I don't know how many strings are in the file, I'm constantly reallocating bigger chunks of memory for the 2d array so I have enough space to store each individual string. For instance, if I type in "hello world" as input to the program, I expect 'h' to be printed out since hello would be the first string and h would be the first character of that string.
size_t size_buffer = 1;
char* buffer = (char*) malloc(size_buffer * sizeof(char)); //initial allocation that can hold 1 single char
size_t cur_nchars = 0; //number of characters read in current string
size_t size_words = 1; //initially only hold 1 string
char** words = (char**) malloc(size_words * sizeof(char*));
size_t cur_nwords = 0; //number of strings read
char read;
while ((read = getchar()) != EOF && !ferror(stdin)) {
if (read == ' ') { //space character
//printf("reached a space character\n");
words[cur_nwords] = buffer; //store string into words string array
cur_nwords++; //increase number of words stored
if (cur_nwords == size_words) { //maximum size hit
size_words *= 2; //multiply old size by 2
char** temp_words = (char**) realloc(words, size_words); //realloc new array twice as big
if (!temp_words) {
printf("can't allocate more memory");
for (size_t i = 0; i < cur_nwords; ++i) {
free(words[i]);
}
free(words);
exit(1);
}
else
words = temp_words; //have old point to new
}
buffer = NULL;
buffer = (char*)malloc(sizeof(char));
cur_nchars = 0;
continue;
}
if (cur_nchars == size_buffer) { //maximum length of string reached
size_buffer *= 2; //new max length is doubled
char* temp = realloc(buffer, size_buffer); //reallocate memory
if (!temp) {
printf("can't allocate more memory");
free(buffer);
exit(1);
}
else {
buffer = temp; //set buffer to point to same location as temp
}
}
buffer[cur_nchars] = read; //store character in char array
cur_nchars++; //increase # chars in string
}
printf("%c", words[0][0]); //throws error!
However after the code exits this loop, the contents of the 2d array words seems to be getting wiped for some reason (can't read memory error)...I have a feeling that I'm not reallocating the memory to the 2d array correctly. Do I need to reallocate the char array strings themselves as well when I'm reallocating the 2d array if the length of the strings themselves aren't changing?