Fixing mem leaks / checking return of fwrite