Skip to content

Instantly share code, notes, and snippets.

@alexpirine
Created June 15, 2012 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alexpirine/2937088 to your computer and use it in GitHub Desktop.
Save alexpirine/2937088 to your computer and use it in GitHub Desktop.
Safe memory allocation in C
void * safe_malloc(size_t const size)
{
void * p = malloc(size);
if (p == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
return p;
}
void * safe_realloc(void * p, size_t const size)
{
p = realloc(p, size);
if (p == NULL) {
fprintf(stderr, "Out of memory\n");
exit(1);
}
return p;
}
@alexpirine
Copy link
Author

This is something that simply ensures that the allocation was done, and terminates the process otherwise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment