MEMSWAP(3pub)

πŸ’… MEMSWAP β€” like, the 3pub manual page, bestie

okay so welcome to publib's very own memswap, straight out of the C Programmer's Manual. sit down, grab a strawberry πŸ“, and let's swap some memory. no cap.


✨ NAME ✨

memswap β€” swap the contents of two memory blocks πŸ”„


πŸ¦‹ SYNOPSIS πŸ¦‹

#include <publib.h>
void memswap(void *block1, void *block2, size_t n);

🌸 DESCRIPTION 🌸

so basically memswap takes the two blocks that your first two args point at and swaps their contents. that's it, that's the whole vibe. the last argument, n, tells it how big those memory blocks are. periodt.


πŸŽ€ EXAMPLE πŸŽ€

say you wanna swap two structs (iconic behaviour honestly), you'd do this:

struct tm tm1, tm2;

memswap(&tm1, &tm2, sizeof(struct tm));

πŸ’€ BUGS πŸ’€

okay bestie, real talk, there are caveats:

  • using memswap to swap small portions of memory is inefficient. it is not worth it to use it to swap variables of any of the basic types, for instance β€” for those cases, just use inline code, fr fr. however, for large portions of memory, e.g., arrays, it is convenient. so like, know your lane. πŸ’…
  • memswap can't swap variables whose address can't be taken. this excludes variables with the register specifier and bitfields in structs. but then, there is no way to write a function (or macro) that can handle any kind of arguments. life is hard. 😭
ngl the "life is hard" thing is literally in the original and honestly? the author ate with that one.

πŸ”₯ SEE ALSO πŸ”₯


πŸ‘‘ AUTHOR πŸ‘‘

Lars Wirzenius (lars.wirzenius@helsinki.fi)


and that's the whole page, angel 🫢 this lil' number lives in Publib's C Programmer's Manual, so if you ever forget it, that's where to find it. go forth and swap responsibly βœ¨πŸ’–

πŸ“¦ where this page comes from