Array-pointer equivalence
In C, an array like the variable buf
in your example is just a pointer to the memory address of the first allocated byte.
You can print the value of this pointer:
#include <stdio.h>
int main(void) {
char buf[10];
printf("Address of the first byte of buf: %p\n", buf);
return 0;
}
Output:
Address of the first byte of buf: 0x7ffd3699bfb6
Pointer arithmetic
When you write something into this buffer with an instruction like
buf[3] = 'Z';
It is in fact translated to
*(buf+3) = 'Z';
It means "add 3
to the value of the pointer buf
and store the character 'Z'
at the resulting address".
Nothing is stopping you from storing the character 'Z'
at any given address. You can store it before or after the address pointed to by buf
without any restriction. If the address you choose happen to be the address of another variable, it cannot produce a segmentation fault (the address is valid).
In C, you can even write the character 'Z'
at the address 123456
if you like:
int main(void) {
char *address = (char *)123456;
*address = 'Z';
return 0;
}
The fact that your buffer is 10 bytes long does not change that. You cannot "fix" this because writing anything at any memory location is a fundamental feature of the C programming language. The only "fix" I can think of would be to use another language.
File descriptors opened at program startup
In your exemple, you pass the value 0
as the first argument of the function read()
. It seems that this value corresponds to the file descriptor of the standard input. This file descriptor is automatically opened at program startup (normally you get such a file descriptor as the result of a call to the function open()
). So, if you get 23 read bytes, it means that you typed in 23 characters on your keyboard during the program execution (for instance, 22 letters and 1 newline character).
It would be better to use the macro name of the standard input file descriptor:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int getinput()
{
char buf[10];
int rv = read(STDIN_FILENO, buf, 10);
printf("\nNumber of bytes read are %d\n", rv);
return 0;
}
int main()
{
getinput();
return 0;
}