Skip to content

copy_to_user()

Purpose

Copies data from kernel memory to a user-space buffer.

#include <linux/uaccess.h>

Prototype

unsigned long copy_to_user(void __user *to, const void *from, unsigned long n);

Parameters

  • to: user-space destination pointer.
  • from: kernel source pointer.
  • n: number of bytes to copy.

Return Value

  • Success: returns 0.
  • Partial/failure: returns number of bytes that could not be copied.

Minimal Example

if (copy_to_user(buf, &value, sizeof(value)))
    return -EFAULT;

Common Pitfalls

  • Return -EFAULT if copy fails.
  • Never dereference user pointers directly.
  • Validate size and state before copying.