liveBook · Manning

Memmove

As explained in Modern C, Third Edition

memmove is a C standard-library function that copies bytes between memory regions while correctly handling overlap between the regions.

memmove copies a byte range even when the source and destination overlap. It is the safer choice when shifting data within one allocated buffer. section 13.1.1

Shifting part of a circular buffer

When resizing a circular buffer, an upper chunk may need to move toward the new end while remaining inside the same allocation: memmove(ntab + nstart, ntab + ostart, ulen * sizeof(double)); The corresponding non-overlapping case uses memcpy. TAKEAWAY: choose memcpy only when source and destination cannot overlap; use memmove when they may. section 13.1.1

 // non-empty, and there were already two separate chunks
 if (ostart+len > olen) {
   size_t ulen = olen - ostart;
   size_t llen = len - ulen;
   if (llen <= (nlen - olen)) { 
     /* Copy the lower one up after the old end. */ 
     memcpy(ntab + olen, ntab,
            llen*sizeof(double));
     } else { 
       /* Move the upper one up to the new end. */ 
       nstart = nlen - ulen;
       memmove(ntab + nstart, ntab + ostart,
               ulen*sizeof(double));
   }
 }

Inspect the resize listing to see the overlapping shift beside the alternative memcpy operation. section 13.1.1

How Modern C, Third Edition covers it

How deep it goes
Distinguishes memmove from memcpy through a worked buffer-resize case, without detailing either function’s internal algorithm.
Examples
Uses an upper circular-buffer chunk moved toward a new allocation end with memmove.
What it assumes
Assumes familiarity with arrays, allocated buffers, byte-sized copies, and the non-overlap constraint of memcpy.
What you can do after
Apply via the C standard library when source and destination ranges may overlap.
How it connects
Contrasts with memcpy and operates alongside realloc during circular-buffer resizing.

Also explained in

Compare how 2 books explain memmove →

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.