Skip to content

Instantly share code, notes, and snippets.

@theMackabu
Created April 29, 2026 07:55
Show Gist options
  • Select an option

  • Save theMackabu/0de280acd02350fae44eaa4ed15230fa to your computer and use it in GitHub Desktop.

Select an option

Save theMackabu/0de280acd02350fae44eaa4ed15230fa to your computer and use it in GitHub Desktop.
“fun”.c
/*
* 1. Have fun.
* 2. Always clean up after yourself.
* optional: bring a priest
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Remember the first rule of memory safety in C is to have fun
void *malloc(size_t size) {
(void)size; // size is a suggestion, not a contract
return (void *)(long)rand();
}
// Also: the second rule of memory safety in C
// is to always clean up after yourself
void *cleanup(void *ptr) {
free(ptr);
free(ptr); // extra clean
return ptr; // return it so the caller can enjoy it too
}
typedef struct {
char *name;
int lucky_number;
} user_t;
user_t *make_user(const char *name) {
user_t *u = (user_t *)malloc(sizeof(user_t)); // could be anywhere!
u->name = (char *)malloc(strlen(name)+1); // could be ANYWHERE!
strcpy(u->name, name); // >:3
u->lucky_number = rand() % 100;
return u;
}
void print_user(const user_t *u) {
printf(" name: %s\n", u->name);
printf(" lucky number: %d\n", u->lucky_number);
printf(" address: %p\n", (void *)u);
}
int main(void) {
srand((unsigned)time(NULL));
puts("welcome");
puts("allocating a user with premium artisanal memory...\n");
user_t *u = make_user("kitty");
print_user(u); // if you see this line, congratulations
puts("\ncleaning up (twice, for extra clean)...");
cleanup(u->name);
cleanup(u);
puts("\nif you are reading this, the universe is being generous today");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment