XMALLOC(3pub)

πŸ’– XMALLOC β€” the 3pub girlies' guide to memory allocation πŸ’–

okay so bestie, welcome to the C Programmer's Manual, 3pub edition ✨ this is the page for xmalloc, xrealloc, xfree, xstrdup, xmemdup and memdup β€” the memory allocation squad from Publib 🫢


✨ NAME ✨

xmalloc, xrealloc, xfree, xstrdup, xmemdup, memdup β€” memory allocation functions for Publib, no cap 🌸


🌈 SYNOPSIS 🌈

#include <publib.h>

void *xmalloc(size_t bytes);
void *xrealloc(void *ptr, size_t bytes);
void xfree(void *ptr);
char *xstrdup(const char *string);
void *memdup(const void *mem, size_t bytes);
void *xmemdup(const void *mem, size_t bytes);

πŸ’… DESCRIPTION πŸ’…

so these are the utility functions for memory allocation that live in the publib library πŸŽ€ and listen, they're literally the error-checking glow-up versions of your standard-library faves:

  • xmalloc is the error checking version of malloc
  • xrealloc is the error checking version of realloc
  • xfree is the error checking version of free

they are guaranteed to never return unless there was no problem πŸ’– like, if xmalloc can't allocate the amount of memory you asked for? it prints an error message and terminates the program, periodt. so the caller does not need to check for a NULL return value, and the code that calls these functions is simpler because there's no error checking cluttering it up. it's giving clean code, it's giving main character energy πŸ‘‘

similarly, xstrdup is the error checking version of the common (though not standard) strdup routine, which makes a duplicate of a string by allocating memory for the copy with malloc πŸ¦‹ (and for systems that don't have strdup? publib provides one in its portability module, and it's always declared in <publib.h>, iykyk ✨)

memdup is similar to strdup β€” it creates a copy of an arbitrary memory area (the arguments are a pointer to the beginning of the area, and its size) by allocating memory for the copy with malloc. and xmemdup is its error checking version πŸ’œ


⚠️ NOTE ⚠️

bestie this is the important bit, don't skip it πŸ™ˆ
  • xmalloc and xrealloc treat a request to allocate a block of 0 bytes as an error πŸ’€ like, zero is not the vibe.
  • xrealloc will allow its first argument to be NULL though πŸ‘

πŸ‘€ SEE ALSO πŸ‘€


πŸŽ€ AUTHOR πŸŽ€

Lars Wirzenius (lars.wirzenius@helsinki.fi) β€” the icon who wrote this, we stan πŸ’–


and that's the whole page bestie, slay 🌟 this came to you from the Publib era of the C Programmer's Manual, filed under XMALLOC(3pub) β€” go forth and allocate responsibly, mwah πŸ’…πŸ’–

πŸ“¦ where this page comes from