cc-standard-library

How does memccpy handle large integer values?


According to man 3 memccpy the memccpy function is defined as follows:

SYNOPSIS

#include <string.h>

void *memccpy(void *dest, const void *src, int c, size_t n);

DESCRIPTION

The memccpy() function copies no more than n bytes from memory area src to memory area dest, stopping when the character c is found.

If the memory areas overlap, the results are undefined.

What confuses me is that memccpy copies n bytes and stops if character c is found. However, the function takes int c as an argument. So what happens if I call memccpy with the following value:

memccpy(&x, &y, 0xffffff76, 100);

Here the value to check is too big for char. Should this case work?


Solution

  • memccpy() is defined by POSIX.1-2001 (IEEE Std 1003.1-2001), which states:

    SYNOPSIS

    #include <string.h>
    
    void *memccpy(void *restrict s1, const void *restrict s2,
           int c, size_t n);
    

    DESCRIPTION

    The memccpy() function shall copy bytes from memory area s2 into s1, stopping after the first occurrence of byte c (converted to an unsigned char) is copied, or after n bytes are copied, whichever comes first. If copying takes place between objects that overlap, the behavior is undefined.

    So there you go, a simple unsigned char conversion takes place:

    void *memccpy(void *restrict s1, const void *restrict s2, int c, size_t n) {
        unsigned char actual_c = (unsigned char)c;
        // ...
    }
    

    In fact, the most prominent C standard library implementations that I know do exactly this: