Of course you get junk. i at that point is 5, which is off the end of the array. You need to give fwrite the pointer to the START of the memory block to be written to the file.