Understanding the behavior of read () and write ()

Hi, I'm a student and I'm just starting to learn low-level programming. I tried to understand the methods read()and write()with this program.

#include <unistd.h>
#include <stdlib.h>
main()
{
    char *st;
    st=calloc(sizeof(char),2);//allocate memory for 2 char
    read(0,st,2);
    write(1,st,2);
}

i expected it to give a segmentation error when I try to enter more than two input characters. But when I run the program and enter “asdf” after providing “how” as output, it executes the “df” command.

I want to know why it does not give a segmentation error when we assign more than 2 char to a string of size 2. and why does it execute the remainder (after 2 char) of input as a command instead of giving it only as output?

also reading the read () man page that I found read () should give an EFAULT error, but that is not the case.

I am using linux.

+3
5

read , , . st, .

, df, , ENTER, , - . Cygwin - . "" UNIX.

EFAULT, st . .


Update:

Ubuntu 9, , . asls, as,

, "", .

, :

asrm -rf /

(, , ).

+3

read() ( read()) . .

+2

(), , . , libc , , . , read() . read() , , ( ), , . , , , libc, / "" .

+1

(0, st, 2); 2 . , , , , , ( df ).

0

2 , . df , :

  • asdf\n
  • as df\n tty
  • ST- stdout
  • df\n df.

, :

  • run your program to trace the system call: strace -e read, write ./yourprogram
  • read(0, st, 5)
0
source

Source: https://habr.com/ru/post/1748470/


All Articles