> The issue in this code is related to memory access. The line data[n] = '\0'; should be (data)[n] = '\0';.
And then went on to generate corrected code and this explanation:
> The original expression, data[n], first applies the array subscript operation, which is equivalent to (data + n), and then tries to dereference the resulting pointer, which is not the intention here. This will likely lead to a segmentation fault because data is a pointer to pointer, and data[n] will try to access memory that has not been allocated.
> The corrected expression, (*data)[n], first dereferences data to get the allocated char array, and then applies the array subscript operation to set the null terminator at the correct location.
I'm not trying to say this isn't impressive, but seems fairly obvious and more like something a linter / analyzer would pickup ?
Actually, no, let's talk about the bug. What's with people's obsession of eliminating local temporaries and working straight with pointer-to-result?
char *buff = malloc(n + 1);
if (fread(buff, 1, n, f) != n) {
free(buff);
fclose(f);
return false;
}
buff[n] = '\0';
*data = buff;
ok:
fclose(f);
return true;
This way, data won't contain a freed pointer when reading fails.