I've stumbled upon following problem: I wrote a program in C, which functions as a variation of Mergesort, just with forking. For this problem, I wrote a function which reads exactly one line from some input stream specified by a parameter, adds a '\0' at the end, and returns a boolean, indicating whether a newline character exists or not. The source code is below:
static bool getInputLine(FILE *f, char **input, int *size_in) {
int size = 0;
char todo;
do {
if((*input = realloc(*input, (size + 1) * sizeof(char))) == NULL) exitWithStatus(EXIT_FAILURE, "reallocing FAILED");
todo = fgetc(f);
if(todo == EOF) break;
(*input)[size] = todo;
if(todo == '\n' && size == 0){
fprintf(stdout, "\n");
break;
}
size++;
} while(todo != '\n');
if((*input = realloc(*input, (size+1) * sizeof(char))) == NULL) exitWithStatus(EXIT_FAILURE, "reallocing FAILED");
(*input)[size] = '\0';
*size_in = size;
return size == 0 || todo != '\n';
}
The code works for (almost) any input, at least so I thought. For some reason, if a line is greater than exactly 26 chars, I get:
realloc(): invalid next size Aborted (core dumped)
I'm relatively new to C, and this had me confused as ever. Any help is greatly appreciated, thanks in advance!
My OS is Linux Fedora, if that helps in any way. Should you need anything else, please let me know :)
And just fyi, the input String is malloc'd with sizeof(char) before calling the function! It is freed again at exiting the process.
EDIT: Despite help from various sides, I have not been able to solve this issue. I had to generally rethink my strategy to solve the problem as a whole. I suppose it had something to do with global variables being inherited by the forked child processes, and hence borking the heap structs in some way or another. Unfortunately, I lost track of what happened exactly, despite restructuring my code to make it more debug-friendly. Thank you very much for your help regardless! :)