Hi there I am trying to write a program that will create memory during run time, such that the program could run continuously as it generates memory to store strings until the user decides to quit. However, when I run the program I can enter the strings properly, however printing them out is another story. I believe the issue is that in the loop I am overwriting the memory that was created through each iteration. Here is what I have thus far:
int main(){
char **lines = NULL;
char sentence[1000];
int numOfLines = 1;
int i;
int j;
printf("Enter the sentence:\n");
lines = (lines, numOfLines * sizeof *lines);
for (i=0; i <= numOfLines; i++){
fgets(sentence, 1000, stdin);
lines[i] = malloc (sizeof(char) * strlen(sentence) +1);
if (strcmp(sentence, ".\n") == 0){ //exits loops if entered string is "."
break;
}
strcpy(lines[i], sentence);
numOfLines++;
printf("%s", lines[i]); // attempt at a Debug statement
}
numOfLines = numOfLines - 1;
for (j = numOfLines; j>=0; j--){ //prints out the lines in reverse
printf("%s\n", lines[j]);
}
return 0;
}
I might add that I get a segmentation fault when the user exits the loop.