1
#include<stdio.h>
#include<stdlib.h>
int main()
{
 int *buffer;
 int i;
 FILE *fp;
 buffer=(int *)malloc(256);
fp=fopen("BACKING_STORE.bin", "r");  //BACKING_STORE.bin is a binary file of size 65K bytes
fseek(fp, 0, SEEK_SET);              //and I am trying to read 256 bytes at a time and storing 
fread(buffer, 256, 1, fp);           //it into buffer of size 256 bytes and printing that buffer
 printf("Data=%d\n", buffer);        //on screen.

 fclose(fp);
}

When I run this program, I get garbage values in result. I know this because in the fseek() function I change offset. Like first when I take offset as 0 it gives me some value let's say 12342539 then I change offset to 256 it gives me output as 14562342 and again when I set offset to 0 it gives me a different output 15623478. So this is how it is showing output which is garbage.

user3386167
  • 65
  • 1
  • 1
  • 6
  • 1
    Try using `fopen("filename.bin", "rb");` for binary files. – Stefan Marinov Mar 06 '14 at 02:05
  • mode 'b' strictly for compatibility with C89 and has no effect; the ''b'' is ignored on all POSIX conforming systems, including Linux. I don't think it's the reason. The point is printf, you print the address from malloc, it's different every time definitely, even maybe run the same program twice! correct the print line is ok enough. – A Lan Mar 06 '14 at 03:02

2 Answers2

2

You're not printing the contents of your buffer, you're printing its address (truncated/cast to an int). Change:

printf("Data=%d\n", buffer);

to:

printf("Data=%d\n", buffer[0]);

or even

printf("Data=%d %d %d %d...\n", buffer[0], buffer[1], buffer[2], buffer[3]);

Other points to note:

  • do not cast the result of malloc in C - it's unnecessary and potentially dangerous

  • use "rb" rather than "r" when opening binary files - this does not matter on most platforms, but it can be a problem on Windows

  • always enable compiler warnings (e.g. gcc -Wall ...) - this would have enabled you to identify and fix your bugs immediately at compile-time instead of puzzling over the unexpected output at run-time

Community
  • 1
  • 1
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 1
    Wanted to comment here because I really like this answer. -Wall has saved me more hours than I care to admit over silly issues that don't result in a compiler error but are flat out wrong. And yes, no need to cast a malloc call, this needs to be one of the first things taught when teaching about pointers and malloc in any respectable class involving C. – James H Mar 06 '14 at 02:52
1

try this

buffer=malloc(256);
fp=fopen("BACKING_STORE.bin", "rb");
fread(buffer, 256, 1, fp);
fclose(fp);
printf("Data=\n");
for(i = 0; i<256/sizeof(int);++i){
    printf("%d\n", buffer[i]);
}
free(buffer);
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70