Skip to content

copy_from_user()

Purpose

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

#include <linux/uaccess.h>

Prototype

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

Parameters

  • to: kernel destination pointer.
  • from: user-space 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

char kbuf[32];
size_t n = min(count, sizeof(kbuf) - 1);
if (copy_from_user(kbuf, buf, n))
    return -EFAULT;

Common Pitfalls

  • Always limit the copy length.
  • Add string termination yourself if treating data as text.
  • Never trust user-provided sizes blindly.