liveBook · Manning

Memcpy

As explained in Modern C, Third Edition

memcpy is a C standard-library function that copies a specified number of bytes from one nonoverlapping memory region to another.

memcpy copies exactly len bytes from source to target. Include <string.h>, provide distinct, nonoverlapping arrays, and ensure both regions can hold the requested length. section 6.1.5

Copying a program name

A small program computes argv[0]'s length with strlen, creates a len+1 character array, and calls memcpy(name, argv[0], len). The separate zero-initialized terminator lets strcmp confirm the copied text. section 6.1.5

TAKEAWAY rules:

  • Pass the copy length explicitly; memcpy does not determine a string length. section 6.1.5
  • Use memcpy for known array regions, while string functions handle zero-terminated strings and their string-specific rules. section 6.1.5

How Modern C, Third Edition covers it

How deep it goes
Defines the prototype, explicit length, and nonoverlap requirement, then demonstrates a complete program without descending into implementation internals.
Examples
Demonstrates copying argv[0] into a zero-initialized variable-length character array and checking it with strcmp.
What it assumes
Assumes familiarity with C arrays and character strings while distinguishing array length from zero-terminated string length.
What you can do after
Apply it via <string.h> to copy a specified number of bytes between suitable nonoverlapping memory regions.
How it connects
Connects memcpy with character arrays, strings, strlen, strcmp, strcpy, memcmp, and memchr.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.