I realize this general issue (inputting strings of variable length in C) has been addressed in myriad locations before, but I'm interested in knowing why my specific approach is not working. (BTW I'm intentionally keeping the size increments small so that I can more easily follow what's going on. After it works on a small scale, I can increase the size to something more reasonable. The main motivation for this approach is that I want to increase the size by a fixed increment, not by doubling the allocated memory each time.)
Here is the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SIZE 4
int main(void)
{
int mem = SIZE;
char *str = malloc(mem); // let's keep str pointing to beginning of string...
char *next_read = str; // ...and next_read pointing to where next character should go
fgets(next_read, mem, stdin);
next_read--; // so that after we add SIZE to pointer, it points to current '\0'
while(str[strlen(str)-1] != '\n') // if we got whole string, the last char will be '\n'
{
mem += SIZE;
str = realloc(str, mem);
next_read += SIZE;
fgets(next_read, SIZE+1, stdin); // read the rest (hopefully) of the line into the new space
printf("str is now %s\n", str);
}
printf("final str is %s", str);
// free(str);
return 0;
}
The code works fine for short strings, but stops working (program seems to get stuck) if string is longer:
bruno@thinkpad:~/Desktop434$ gcc getstring.c
bruno@thinkpad:~/Desktop436$ ./a.out
I love linux
str is now I love
str is now I love linu
str is now I love linux
final str is I love linux
bruno@thinkpad:~/Desktop436$ ./a.out
I love linux and the C programming language
str is now I love
str is now I love linu
str is now I love linux an
str is now I love linux and th
str is now I love linux and the C
str is now I love linux and the C
str is now I love linux and the C
str is now I love linux and the C
str is now I love linux and the C
str is now I love linux and the C
str is now I love linux and the C
I'm a newbie in C and would like to learn something by debugging this.