Skip to content

Instantly share code, notes, and snippets.

@hpcx82
Created June 17, 2012 01:50
Show Gist options
  • Save hpcx82/2943127 to your computer and use it in GitHub Desktop.
Save hpcx82/2943127 to your computer and use it in GitHub Desktop.
#algorithm# memory copy
#include <stdio.h>
// A homemade memcpy function.
// 1. Handle the memory overlap
// 2. Copy 4 bytes a time first as int, then copy the left ones as char (at most 3)
void* mymemcpy(void* dest, const void* src, size_t count)
{
if(NULL == dest || NULL == src || dest == src)
return dest;
size_t num_int = count / sizeof(int);
size_t num_byte = count % sizeof(int);
int* piDest = (int*)dest;
int* piSrc = (int*)src;
char* pcDest = (char*)dest + num_int * 4;
char* pcSrc = (char*)src + num_int * 4;
// pSrc->pDest overlap
if(pcDest > pcSrc && size_t(pcDest-pcDest) < count)
{
// this for must come first
for(size_t i = num_byte; i >= 1; i--)
{
pcDest[i-1] = pcSrc[i-1];
}
for(size_t i = num_int; i >= 1; i--)
{
piDest[i-1] = piSrc[i-1];
}
}
// no overlap or pDest->pSrc overlap
else
{
for(size_t i = 0; i < num_int; i++)
{
piDest[i] = piSrc[i];
}
for(size_t i = 0; i < num_byte; i++)
{
pcDest[i] = pcSrc[i];
}
}
return (void*)dest;
}
int main()
{
// non overlap
char name[100] = "I am Henry";
char newname[100];
char* mynewname1 = (char*)mymemcpy(newname, name, 11);
printf(mynewname1);
printf("\n");
// overlap
char* p = name + 3;
char* mynewname2 = (char*)mymemcpy(p, name, 11);
printf(mynewname2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment