Reputation: 433
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
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
Accessing memory you do not own is undefined behaviour, often honored with segmentation fault.
Upvotes: 3
Reputation: 55
replace %s with %c .. %c is for single character %s is for a string (more than 1 charachter)
Upvotes: 1
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
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