I’m learning C and I don’t understand the behavior of the code below:
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int buffer;
read(0, &buffer, sizeof(int));
printf("%d", buffer);
return 0;
}
Input:
1
Output:
2609
What’s going on here? Shouldn’t the output be 1?
You are confusing
1, the decimal digit, with one, the number. You are also confusing the number one with the computers internal representation of the number one.A person hitting the
1key on the keyboard is not typing in the computer’s internal representation for the number one. So reading that key directly into an integer variable will give garbage.The computer internally stores 2609 as 0x31, 0x0A (assuming little-endian). When the person hits
1and then enter, the keyboard sends an 0x31 (the ASCII code for1) and then an enter (0x0A).But this is a case of garbage in, garbage out. You shouldn’t pass the address of an integer to a function that doesn’t expect a pointer to an integer.