|
Implement and test a memcpy function
|
|
The function copies memory block pointed by src into memory block pointed by dst.
1. Request the types of arguments and return value (thus determing the real declaration: void memcpy( void* src, void* dst, size_t size );
2. Request the units of size.
3. Mention the case of overlapping src and dst blocks. Be very careful about this case.
void memcpy( void* src, void* dst, size_t size )
{
char *pc_src = src, *pc_dst = dst; //in C++ this will require an explicit cast
if(pc_dst <= p_src )
for( char* it_src = pc_src, *it_dst = pc_dst; it_src < pc_src + size_t; it_src++, it_dst++ )
*it_dst = *it_src;
else
for( char* it_src = pc_src + size-1, *it_dst = pc_dst + size-1; it_src >= pc_src; it_src--, it_dst-- )
*it_dst = *it_src;
}
Now I'm too lazy to write the tests, but do mention the cases:
1. A usual case. Also check that the memory around src and dst doesn't change.
2. A case of overlapping blocks: src before and beyond dst. Also src and dst at the same address.
3. size = 1 and size = 0 cases.
4. You may be asked to write a case when memory is copied between different data types (e.g. unsidned int and char[4])
|
|