Skip to content

Instantly share code, notes, and snippets.

@syenchuk
Created June 15, 2012 15:38
Show Gist options
  • Select an option

  • Save syenchuk/2937088 to your computer and use it in GitHub Desktop.

Select an option

Save syenchuk/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;
}
@syenchuk

Copy link
Copy Markdown
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