/dev/hello_world: A Simple Introduction to Device Drivers under Linux
Subject:   Small problem in hello_proc.c?
Date:   2007-07-08 06:12:15
I think there is a small problem in hello_proc.c.

First you check whether "size" is small then "len" and if so, return -EINVAL.

If not (and offset==0), you do strcpy(buffer, hello_str); but strcpy() will copy strlen(hello_str) + 1 bytes (since it also copy a '\0' to "buffer").

If size==len, the buffer only has enough space for "len" bytes, but you're copying "len"+1 bytes.

Shouldn't it be something like

if(size <= len)
return -EINVAL;


Main Topics Oldest First

Showing messages 1 through 1 of 1.

  • Small problem in hello_proc.c?
    2007-07-08 11:47:27  valhenson [View]

    Yes, you are correct that we are copying one more byte to the buffer than we are testing for. Thanks for catching the bug! In practice, this isn't a problem because the kernel always allocates a full page to pass to the /proc read function. The solution isn't to test for a larger buffer, though - we don't want to copy the null terminating byte to userspace. Instead, we'll use strncpy to avoid copying the terminating byte.

    * We know the buffer is big enough to hold the string. Don't
    * copy the terminating '\0' - this is file output, not
    * another C string.
    strncpy(buffer, hello_str, len);