4 ms·
I'm not massively great at C but would this be a fix? void* memmove(void *vdst, void *vsrc, int n) { char *dst, *src; dst = vdst;
by antihero 15y ago
I'm not massively great at C but would this be a fix?
void*
memmove(void *vdst, void *vsrc, int n)
{
char *dst, *src;
dst = vdst;
src = vsrc;
if(*vdst > *vsrc) {
*vdst += n;
*vsrc += n;
while(n-- > 0)
*dst-- = *src--;
}
else if(*vdst < *vsrc)
while(n-- > 0)
*dst++ == *src++;
return vdst;
}
- unwantedLetters 15y agoI think this might have an off-by-one error in the case you've corrected. I'm not sure I remember how to write this in C, the correction might be: --dst = --src; OR (--dst) = (--src); edit: I have the dereferences in there, but I don't know how to correctly format it so they show up. How do you format the comment to have code show up?
- abecedarius 15y agoAt least two bugs: the test should compare vdst to vsrc, not * vdst to * vsrc, and in the first branch you're copying vsrc[n] which is out of range (and skipping vsrc[0]).
- antihero 15y agoThe first bug I'm confused? Surely we want to use the * because we're comparing the position in memory, not what's in the memory? Or does the * mean "compare what is in that memory slot"? Second bug, cheers. http://news.ycombinator.com/item?id=3214807 http://news.ycombinator.com/item?id=3214807
- simcop2387 15y agoI see an additional bug in there compared to the original, you're copying the memory below vsrc into the memory below vdst in the first branch. you need to add to dst and src not vdst/vsrc.
- antihero 15y agoThanks, C rather rusty :) http://news.ycombinator.com/item?id=3214807 http://news.ycombinator.com/item?id=3214807
- antihero 15y agoOk, updated version: void* memmove(void *vdst, void *vsrc, int n) { char *dst, *src; dst = vdst; src = vsrc; if(vdst > vsrc) { dst = vdst + n; src = vsrc + n; while(n-- > 0) *--dst = *--src; } else if(vdst < vsrc) while(n-- > 0) *dst++ == *src++; return vdst; } Does this solve the bugs?
- abecedarius 15y agoThere's an == for an =. Also vdst+n is an error, I believe, because sizeof *vdst has no meaning.