samedi 27 juin 2015

memccpy return lower memory address than the src starting address

I've got a school project where I have to recode the memccpy() function.

Here is my code:

void    *ft_memccpy(void *str_dest, const void *str_src, int c, size_t n)
{
    unsigned int    i;
    char            *dest;
    char            *src;
    char            *ptr;

    dest = (char *)str_dest;
    src = (char *)str_src;
    i = 0;
    ptr = 0;
    while (i < n && ptr == 0)
    {
        dest[i] = src[i];
        if (src[i] == ((char)c))
            ptr = dest + i + 1;
        i++;
    }
    return (ptr);
}

I use 2 programs to check if my code works properly and when I test my function in an unique program, it works.

void main(void)
{
    char    src[] = "Ceci est un test.";
    char    dest[200];
    void    *ptr, *ptr2;

    ptr = ft_memccpy(dest, src, 'i', 10);
    ptr2 = memccpy(dest, src, 'i', 10);
}

With the code above, the two function return the same exact address.

But with another test program the memccpy() function return an address lower than the first character of the src pointer.

For example:

  • Starting address of the src value: Ptr found: 0x7fff712edc40
  • Memccpy return pointer address: 0x712edc44
  • My memccpy function return pointer: 0x7fff712edc44

Here is the code that provides this behavior:

char    buf1[] = "Ceci est un test.";
char    buf2[200];
void    *p1, *p2;

p1 = memccpy(buf2, buf1, 'i', 10);
p2 = ft_memccpy(buf2, buf1, 'i', 10);

So I don't really understand because the two program have the same code, except that the second is much bigger.

Does somebody know what can cause this kind of behavior?

  • I tried to search on Google but the answer was not very helpful.
  • I read the man multiple times ^^' (not more helpful).
  • I read that memccpy have an undefined behavior when memory overlap, but they don't overlap.

Aucun commentaire:

Enregistrer un commentaire