You are calling malloc
with the product of num
and sizeof(char)
. The value num
is not initialized to anything. So you are allocating a random amount of memory when you call malloc
. You should set num
equal to the number of bytes you intend to read in or greater. I suggest modifying your code along these lines
num = 100;
buffer = malloc(sizeof(char)*num))
int err = fread(buffer,sizeof(char),num,fp);
In this way you will not read in more data than is available in buffer
. Also, you should check the return values of fread
and malloc
for possible errors. malloc
can return the NULL pointer on error, and fread
can return zero. You'll need to use ferror
to get the exact error.