Memory Copy

Allows copying from source memory address to destination memory address.

Also be aware of memmove.

Resources

Usage

/* memcpy example */
#include <stdio.h>
#include <string.h>
 
struct {
  char name[40];
  int age;
} person, person_copy;
 
int main ()
{
  char myname[] = "Pierre de Fermat";
 
  /* using memcpy to copy string: */
  memcpy ( person.name, myname, strlen(myname)+1 );
  person.age = 46;
 
  /* using memcpy to copy structure: */
  memcpy ( &person_copy, &person, sizeof(person) );
 
  printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
 
  return 0;
}

What happens under the hood when you call memcpy?

Both hardware and software are involved.

  • Software: The memcpy function requests the OS to allocate memory for the operation.
  • Hardware: Once the memory is allocated, the actual data transfer is handled by the CPU. The MMU in the CPU ensures that the data is physically moved from one memory location to another.

Note that modern CPUs can optimize such operations through techniques like Prefetching and efficient Caching.

Cuda

Use cudaMemcpy.