Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't there a standard memswap function

Tags:

c

Why doesn't have the c standard a memswap function, which would probably look like:

int memswap(void *ptr1, void *ptr2, size_t nbytes)?

I know it'd be easy to write, but i think the libc could do some awesome tricks to speed it up like some implementations do it for memcpy.

like image 616
quinmars Avatar asked Sep 20 '08 20:09

quinmars


2 Answers

I think because it's not needed very often. However, there is an easy way to do this in C++:

#include <algorithm>

swap_ranges(ptr1, ptr1 + nbytes, ptr2)

It's it may not be quite as optimized as a compiler built in, but it has the potential of being faster than a loop you write for yourself, since it may have platform specific optimization that you would not implement.

You do need to be careful with the above, because it assumes that ptr1 and ptr2 are char pointers. The more canonical way to do this is:

#include <algorithm>

swap_ranges(ptr1, ptr1 + num_items, ptr2)
like image 150
dvorak Avatar answered Oct 29 '22 21:10

dvorak


This isn't something that is routinely required.

The ideas may have been considered and discarded because it is quite difficult to come up with an algorithm that is general purpose. Don't forget that C is an old language and extensions need to be generally useful.

Possible error conditions :-

  • behaviour when the ranges being swapped overlap
  • length of zero
  • running out of memory (an optimal implementation might allocate memory to do this)
  • null pointer

The best algorithm might also depend upon what you are doing, and so could be better coded directly by you.

  • swapping structures likely to be quicker using a temp structure and assignment
  • small lengths - may be better allocating temporary memory
  • long lengths - 'section' by section swap (where section is some optimal length)
  • use of hardware copy functions
like image 24
itj Avatar answered Oct 29 '22 23:10

itj