Return to Snippet

Revision: 38540
at January 4, 2011 23:45 by blackthorne


Initial Code
Add this function:

#include <stdlib.h>
#define MALLOC_ERROR -1
...
static void *checked_malloc(const size_t size)
{
  void *data;

  data = malloc(size);
  if (data == NULL)
    {
      fprintf(stderr, "\nOut of memory.\n");
      fflush(stderr);
      exit(MALLOC_ERROR);
    }

  return data;
}
(can be improved with calloc() usage and realloc())

Then, invoke the method with:

char *new_data;
size_t whatever_u_need = 20;
new_data = checked_malloc(whatever_u_need);

Initial URL


Initial Description
In C, you have to manage your own program's memory. So if you allocate memory using malloc() you should not forget to free() it when no longer required.

You should also make sure if there is available memory in your system to allocate.

Initial Title
malloc() memory allocation handling

Initial Tags


Initial Language
C