title: copy_to_user vs memcpy
body: <p>I have always been told(In books and tutorials) that while copying data from kernel space to user space, we should use copy_to_user() and using memcpy() would cause problems to the system. Recently by mistake i have used memcpy() and it worked perfectly fine with out any problems. <strong>Why is that we should use copy_to_user instead of memcpy()</strong></p>
  
  <p>My test code(Kernel module) is something like this:</p>
  
  <pre><code>static ssize_t test_read(struct file *file, char __user * buf,
               size_t len, loff_t * offset)
  {
      char ani[100];
  
      if (!*offset) {
          memset(ani, 'A', 100);
          if (memcpy(buf, ani, 100))
              return -EFAULT;
          *offset = 100;
          return *offset;
      }
  
      return 0;
  }
  
  struct file_operations test_fops = {
      .owner = THIS_MODULE,
      .read = test_read,
  };
  
  static int __init my_module_init(void)
  {
      struct proc_dir_entry *entry;
  
      printk("We are testing now!!\n");
      entry = create_proc_entry("test", S_IFREG | S_IRUGO, NULL);
      if (!entry)
          printk("Failed to creats proc entry test\n");
  
      entry-&gt;proc_fops = &amp;test_fops;
      return 0;
  }
  module_init(my_module_init);
  </code></pre>
  
  <p>From user-space app, i am reading my <code>/proc</code> entry and everything works fine.</p>
  
  <p>A look at source code of copy_to_user() says that it is also simple memcpy() where we are just trying to check if the pointer is valid or not with access_ok and doing memcpy.</p>
  
  <p>So <strong>my understanding</strong> currently is that, <strong>if we are sure about the pointer we are passing, memcpy() can always be used in place of copy_to_user</strong>.</p>
  
  <p>Please correct me if my understanding is incorrect and also, <strong>any example where copy_to_user works and memcpy() fails would be very useful</strong>. Thanks.</p>