nineties
nineties

Reputation: 433

Segmentation fault (core dumped) case with fread

Would some please tell me why this code leads to such an error?

unsigned char buffer;
fread(&buffer,1,1,image_ptr);
printf("%s ",buffer);

The image is 8-bit grayscale. Thank you.

Upvotes: 0

Views: 583

Answers (4)

Xie
Xie

Reputation: 374

Because you read one byte into the buffer and treat it as an 0-terminated string in printf. This will interpret the memory at @buffer as a pointer to char (on most modern machines 4 or 8 bytes long) and then print bytes starting at that memory address until a 0 is found.

This way you tell printf to

  • first read 3-7 bytes behind the variable buffer
  • and the read bytes from a completely random memory address

Accessing memory you do not own is undefined behaviour, often honored with segmentation fault.

Upvotes: 3

Waseem Gabour
Waseem Gabour

Reputation: 55

replace %s with %c .. %c is for single character %s is for a string (more than 1 charachter)

Upvotes: 1

Kninnug
Kninnug

Reputation: 8053

The %s specifier is for strings i.e. a char *, you're passing a char, which isn't the same.

Use %c in printf to print buffer:

printf("%c ", buffer);

Upvotes: 5

Carl Norum
Carl Norum

Reputation: 225202

%s is the format specifier to print a string, but buffer is not a string. That causes undefined behaviour. You want %c or maybe %u or %x depending on what you want as output.

Upvotes: 5

Related Questions