NAME
maybealloc – allocate memory, maybe
SYNOPSIS
#include <maybe.h>
void *maybealloc(size_t size);
void *mayberealloc(void *ptr, size_t size);
void *borrowalloc(size_t size);
void probablyfree(void *ptr);
int wasitfreed(const void *ptr);
Link with -lmaybe. Sometimes.
DESCRIPTION
maybealloc() allocates size bytes and returns a pointer to them. Maybe.
libmaybe decides at runtime, based on system load, the phase of the moon and
whether the calling program has already forgotten a free() today. (It has.)
mayberealloc() changes the size of a memory block. The new block may be larger, smaller or a different one altogether. Its contents are preserved, provided they were important. libmaybe decides whether they were important.
borrowalloc() borrows memory from another process. The memory is returned as soon as the other process notices.
probablyfree() frees memory, probably. Calling it several times for the same pointer is explicitly allowed. What other libraries call a "double free", libmaybe calls redundancy.
wasitfreed() answers the question every C programmer asks at three in the morning.
RETURN VALUE
maybealloc(),mayberealloc(),borrowalloc()- A pointer to the allocated memory,
NULLon error, orMAYBE, defined as(void *) 0x5050. A pointer toMAYBEmay be dereferenced if you dare. The result is alsoMAYBE. wasitfreed()1for yes,0for no,-1for "don't ask",-2for "ask Valgrind".
ENVIRONMENT
MAYBE_CONFIDENCE- A value between 0 and 100, default 50. At 100, maybealloc() behaves like malloc(), only slower and with a guiltier conscience. At 0, maybealloc() always returns
NULL, but is very honest about it.
EXAMPLES
char *buf = maybealloc(1024);
if (buf == NULL) {
/* Out of memory. */
} else if (buf == MAYBE) {
/* Schrödinger's buffer: allocated until somebody checks. */
} else {
strcpy(buf, "Hello, heap");
puts(buf);
probablyfree(buf);
probablyfree(buf); /* better safe than sorry */
}
The same program, run four times in a row:
$ ./program
Segmentation fault (core dumped)
$ ./program
Segmentation fault (core maybe dumped)
$ ./program
Hello, heap
$ ./program
Hello, heap (borrowed from process 3117)$ valgrind ./program
==4242== HEAP SUMMARY:
==4242== in use at exit: maybe 1,024 bytes in maybe 1 blocks
==4242== All heap blocks were possibly freed -- no leaks are possibleBUGS
Under load, maybealloc() occasionally returns memory that belongs to another process. The other process receives an apology and a voucher.
Rust developers are asked to stop reading this page now. Too late – they're already writing a comment.