This question is definitely related to this and it’s answer is what I based my function off of.
char *get_next_line(FILE *fp) {
char ch = 0;
int CUR_MAX = 4095;
char *buffer = (char*) malloc(sizeof(char) * CUR_MAX); // allocate buffer.
char *temp = (char*) malloc(sizeof(char) * CUR_MAX); // allocate buffer.
int count = 0;
int length = 0;
while ((ch != '\n')) {
if (ch == '\377') { return NULL; }
if(count ==CUR_MAX) {
CUR_MAX *= 2;
count = 0;
if ((temp = realloc(buffer, CUR_MAX)) != NULL) {
buffer = temp;
free(temp);
}
}
ch = getc(fp);
buffer[length] = ch;
length++;
count++;
}
For some reason, when reading in very large strings I’m faced with:
glibc detected – realloc() invalid next size.
Is there something I’m missing here?
Thanks!
I believe you’re accessing memory outside of your malloced/realloced region.
Not setting
count = 0inside your while look should fix this.To try and elaborate…
When starting the formula:
These will increment until they reach 4095. Once we reach 4095, we will have:
We will then increment until count is 8190. Shorly before then, we have:
Your array is only 8190 in length, but you’re dereferencing
buffer[12196], which is an invalid index.Also, you probably want to handle the
elsecase for whentemp == NULL. This probably can be handled by anassertor a big old failure. And don’tfree(temp)inside your success side. That’s freeing the memory you just attempted to allocate. And is causing your new segmentation fault.