c - why is memmove garbling first few bytes -


i writing hobbyos. want copy small section of memory 1 spot another. somehow memmove function keeps garbling first few bytes , first few bytes.

this memmove function:

void* memmove(void *dst, const void *src, uint32_t n) {   const char *s;   char *d;    s = src;   d = dst;   if(s < d && s + n > d){     s += n;     d += n;     while(n-- > 0)       *--d = *--s;   } else     while(n-- > 0)       *d++ = *s++;    return dst; } 

i call function so:

char *dest char *origin     memmove(dest, origin, 100); 

when inspect memory after (i using boschs) odd discrepancy in first few bytes, after copied expected:

original @ 0x502220: 0x0000000000502220 <bogus+       0>:    0x50224468  0x223c6800  0x006a0050  copy @ 0x0: 0x0000000000000000 <bogus+       0>:    0x00504460  0x223c6800  0x006a0050 

as can see, first 4 bytes garbled. rest copied expected.

what causing behavior?

  1. following ub. cannot reliably compare < <= >= > 2 pointers not of same array, object.

    if(s < d && s + n > d){ 

when 2 pointers compared, result depends on relative locations in address space of objects pointed to. if 2 pointers object types both point same object,... if objects pointed members of same aggregate object, ... pointers members of same union object ... in other cases, behavior undefined.
c11dr §6.5.8 5 relational operators

  1. it more canonical use size_t n rather uint32_t n.

  2. in below usage, both dest, src not initialized @bathsheba delted answer. based on user info, appear code attempted write address 0. system prevents that. ub using uninitialized pointers.

    char *dest char *origin     memmove(dest, origin, 100); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -