ErrorCode readFile(char *fileName, char **fileContent, size_t *size) {
FILE *f = fopen(fileName, "r");
if (!f) {
fprintf(stderr, "Error opening file %s\n", fileName);
return READ_FILE_OPEN_ERROR;
}
char *buffer = malloc(CHUNK_SIZE);
if (!buffer) {
fprintf(stderr, "malloc failure\n");
return READ_FILE_MALLOC_FAILURE;
}
size_t bufferSize = CHUNK_SIZE;
size_t bytesRead;
size_t i = 0;
while ((bytesRead = fread(buffer + i, 1, CHUNK_SIZE, f))) {
i += bytesRead;
if (bytesRead == CHUNK_SIZE) {
char *temp = realloc(buffer, bufferSize += bytesRead);
if (!temp) {
fprintf(stderr, "realloc failure\n");
free(buffer);
return READ_FILE_REALLOC_FAILURE;
}
buffer = temp;
}
}
char *temp = realloc(buffer, i + 1);
if (!temp) {
fprintf(stderr, "realloc failure\n");
free(buffer);
return READ_FILE_REALLOC_FAILURE;
}
buffer = temp;
buffer[i] = '\0';
bufferSize = i + 1;
if (ferror(f)) {
fprintf(stderr, "Error reading file %s: %s\n", fileName, strerror(errno));
free(buffer);
fclose(f);
return READ_FILE_READ_ERROR;
}
*fileContent = buffer;
*size = bufferSize;
fclose(f);
return READ_FILE_SUCCESS;
}
this is the relevant section. the function worked for a small test file. now i wanted to test it with a bigger file and suddenly i got an error. when i run the file normally i get my "Error reading file testfile.txt: Invalid argument" print which i do in the code. but when i run it in the debugger (lldb) and set a breakpoint in the if that checks ferror, the breakpoint does not trigger, i just get an other exception because the string is NULL because the if (ferror(f)) block frees it, but why does it not trigger? Also when i completely delete the if (ferror(f)) block then my code works as intended with no problems, so why is the ferror flag true when there is no error?