This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.

Released under the GNU General Public License.

Return to index Return to header Previous symbol Next symbol

memcpy

Prototype

#include <string.h>

void *memcpy(void *dest, const void *src, size_t n);

Description

Copies the data pointed by src into the dest buffer, overwriting the previous existing data. The size in bytes to be copied is specified by the n parameter. The two areas should not overlap. Returns the dest parameter.

Implementation

View source
#include <string.h>

void *memcpy(void *dest, const void *src, size_t n)
{
    char *dp = dest;
    const char *sp = src;

    while (n-- > 0)
	*dp++ = *sp++;

    return dest;
}

Example

View source
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * Duplicate the argument object.
 */
void *objdup(void *ptr, size_t size)
{
    void *nptr;

    if ((nptr = malloc(size)) != NULL)
	memcpy(nptr, ptr, size);

    return nptr;
}

int main(void)
{
    struct s { int a; char c; } obj, *obj2;

    obj.a = 1; obj.c = 'x';
    if ((obj2 = objdup(&obj, sizeof obj)) == NULL) {
	fprintf(stderr, "Cannot allocate memory\n");
	return EXIT_FAILURE;
    }
    if (obj.a != obj2->a || obj.c != obj2->c) {
	free(obj2);
	fprintf(stderr, "Unexpected behavior\n");
	return EXIT_FAILURE;
    }
    free(obj2);

    return EXIT_SUCCESS;
}

References

ISO C 9899:1990 7.11.2.1