OpenBSD Journal

memcpy vs memmove

Contributed by jj on from the memwrite-me-an-article dept.

Ted Unangst (tedu@) took the time to write up a short history of the trials and tribulations that have accompanied the recent attention being paid to the memcpy(3) and memmove(3) routines:

memcpy vs memmove

A few notes about memcpy vs memmove and some related items as well.


The C standard specifies two functions for copying memory regions, memcpy and memmove. The important difference is that it is undefined behavior to call memcpy with overlapping regions. One must use memmove for that. As the names imply, memcpy copies data from one region to another, while memmove moves data within a region. (Itís also perfectly acceptable to memmove between different regions.)

This subtle but important distinction allows memcpy to be optimized more aggressively. In the case of memmove between overlapping regions, care must be taken not to destroy the contents of the source before they are done copying. This is easiest to see with a naive implementation of a copy loop.

Read the whole thing; it's an exciting journey into the world of bug-hunting!

(Comments are closed)


Copyright © - Daniel Hartmeier. All rights reserved. Articles and comments are copyright their respective authors, submission implies license to publish on this web site. Contents of the archive prior to as well as images and HTML templates were copied from the fabulous original with Jose's and Jim's kind permission. This journal runs as CGI with httpd(8) on OpenBSD, the source code is BSD licensed. undeadly \Un*dead"ly\, a. Not subject to death; immortal. [Obs.]