Reputation: 35
I've been trying to figure out what the problem is for hours and can't get it right. Here is the code, which is of course a lot longer but I've reduced it to the problem itself.
#define BUFFER_SIZE 60
char *str;
void readText() {
char read_char;
int i = 0;
str = (char *) calloc(BUFFER_SIZE, sizeof(char));
while ((read_char = getchar()) != EOF) { /* user hits ctrl+d */
*(str+i) = read_char;
i++;
if (i % BUFFER_SIZE == 0) {
str = (char *) realloc(str, BUFFER_SIZE * sizeof(char));
}
}
textSize = i;
/* Here I print the text... same error printing or not printing */
free(str);
}
}
I only get the error when the input text exceeds the buffer size.
(edited: if (i % BUFFER_SIZE == 0) so it makes it every time it get to 60, but the error is the same )
Thanks
Upvotes: 0
Views: 140
Reputation: 41017
That's because you are realloc
ating with the same size, you need to use the new size when the string grows up:
while ((read_char = getchar()) != EOF) { /* user hits ctrl+d */
if (i >= BUFFER_SIZE) {
str = realloc(str, i);
}
*(str+i) = read_char;
i++;
}
Also, it seems that you forget to set the trailing NUL, you need it in order to build a valid (printable) string, switch to
if (i >= BUFFER_SIZE - 1) {
and
str[i] = '\0';
after the while
loop.
Finally, prefer
size_t i = 0; // or better yet size_t len = 0;
over
int i = 0;
to pass the size to realloc
and friends.
Upvotes: 1