Re: Implementing my own memcpy



On Sat, 25 Jun 2005 07:28:30 -0700, Rajan wrote:

> Hi,
> I am trying to simulate a memcpy like this void* mem_cpy(void* dest, void*
> src, int bytes) {
> dest = malloc(bytes);
> }
> Now if I want to copy the bytes from src to dest, how do I copy these
> bytes.
> I am stuck here.

Why can't you use memcpy itself? I'll assume you have a reason that
isn't "it's a homework assignment".

Are you trying to achieve the exact same behaviour as memcpy? If so,
then don't allocate memory - memcpy requires that the memory is already
allocated. The second parameter needs to be qualified with const. Also
the type of the third parameter is size_t not int - this requires that
you include stddef.h. Even if it were declared as int it should be
unsigned.

Here is an implementation:

#include <stddef.h>

void *mem_cpy(void *dest, const void *src, size_t bytes)
{
unsigned char *srcmax = dest + bytes;

while (src < srcmax)
*(unsigned char *)dest++ = *(unsigned char *)src++;
return dest;
}

.



Relevant Pages