I have just started learning C and I've started by doing some projects in this repo, specifically this one. I try not to JUST copy code, but when writing the "readLine" function I ran into something that I just don't see why it's happening or even less so how to fix it.
For context here is the function I wrote:
char *readLine(void){
int buffsize = shbuffsize;
char *buffer = malloc(sizeof(char) * buffsize);
char c;
int pos = 0;
if(CheckMallocError(buffer, "buffer")){ // Checking memory allocation fault
exit(EXIT_FAILURE);
}
while ((c = getchar()) != '\n' || c != EOF) {
if(pos >= buffsize){ // If we exeed the buffers size it needs to be extended
buffsize += shbuffsize;
buffer = realloc(buffer, buffsize);
}
buffer[pos] = c;
pos++;
}
printf("exited"); // NEVER GET HERE
return buffer; // PROBARBLY NOT HERE EITHER
}
As you see by my comments "exited" never gets printed. However, if I put
printf("%i",pos);
on the line beneath pos++;
(still inside the loop) i get correct looking output which to me indicate that that the loop isn't infnite. Example input: "hi" | output: 123
.
Then I decided to test adding a break;
to be certain that I exit the loop. That is when I got the realloc invalid next size
error message. (Compiles fine, the error shows up as soon as i press enter after typing something). For context this is the new code:
char *readLine(void){
int buffsize = shbuffsize;
char *buffer = malloc(sizeof(char) * buffsize);
char c;
int pos = 0;
if(CheckMallocError(buffer, "buffer")){ // Checking memory allocation fault
exit(EXIT_FAILURE);
}
while ((c = getchar()) != '\n' || c != EOF) {
if(pos >= buffsize){ // If we exeed the buffers size it needs to be extended
buffsize += shbuffsize;
buffer = realloc(buffer, buffsize);
}
buffer[pos] = c;
pos++;
break;
}
printf("exited"); // NEVER GET HERE
return buffer; // PROBARBLY NOT HERE EITHER
}
Exact message:
realloc(): invalid next size
[1] 1408 abort
The two functions are identicall execept for that one break statement and it doesn't make sense to me why that would break everything. Especially since we shouldn't even have to extend the buffer for only two characters.