I’m trying to read a file and fill an array with all the characters in the file. The problem is that in the while cycle the execution stops and there is a segmentation fault error. This is the interested function:
void allocAndFillArray(char **arrayChar, FILE *file) {
// *file is checked before the function and
// if the function is called the pointer is not NULL
int len = x; // x is just a random size. In the real function it is the number of characters in the file
*arrayChar = (char *)calloc(len, sizeof(char));
int i = 0;
while (i < len) {
*arrayChar[i] = fgetc(file);
i = i + 1;
} // in this cycle the execution stops after the first iteration
// and only one character is written in the array
// before a crash reported as segmentation fault.
fclose(file);
}
I tried changing calloc with malloc, tried changing the size but it just doesn’t work
>Solution :
Why is calloc function not allocating the array?
You’re not checking whether calloc() succeeded, and you should. But more likely than not, the answer to the title question is that calloc() in fact is allocating the array.
The problem is that in the while cycle the execution stops and there is a segmentation fault error.
That’s almost surely because your function is buggy. Here …
*arrayChar[i] = fgetc(file);
… you appear to want this, instead:
(*arrayChar)[i] = fgetc(file);
They do not mean the same thing. The [] operator and all other postfix operators have the highest precedence of all operators, so your original statement is equivalent to
*(arrayChar[i]) = fgetc(file);
, which almost certainly overruns the bounds of the object designated by *arraychar if i reaches more than a very small number — likely if it reaches even 2, though that might not be enough to trigger a segfault.