简体   繁体   中英

What happen if buffer size is too small to hold the read data return by read() system call?

Consider the program bellow, What happens when the program is executed?

 #include <fcntl.h>
 #include <stdio.h>
 #include <string.h>
 main()
 {
    int fd;
    char buf[256];
    fd=open("/etc/passwd",O_RDONLY);
    if(read(fd,buf,1024)<0)
       printf("read fail\n");
    printf("strlen%d:\n",strlen(buf));
}

I think read system call will copy 1024 byte from kernel buffer to buf and the result should be "strlen:1024"

But I execute it in gcc 4.1, the result is:

strlen:1024
segment fault

I'm wondering why there is a segment fault?

At least,if there should be,why not throw a segment fault immediately in read system call but after printf "stelen:1024"?

Any help will be appreciated.

It looks like you're willingly copying 1024 bytes into a stack-allocated 256-byte buffer. This results in undefined behavior . Anything can happen.

In your specific case, read() happily writes past your buffer and overwrites part of the stack, including the return address of the currently executing function. Nothing too serious happens until main() tries to return into an unmapped portion of the memory space, and then your program segfaults.

Also note that, as wildplasser rightfully points out in his comment, it looks like the part of the stack that gets overwritten is still zero-filled, so strlen() finds a terminating \\0 character at index 1024 and does not wander into unmapped territory itself.

This behavior is, of course, completely unreliable, and can change if you slightly modify your program, or even between runs of the same program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM