Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

assert ( malloc...

Name: Anonymous 2010-06-28 13:36

A question for you, Anon.

If you watch at malloc() manpage you can notice that the function may return NULL in some cases (i.e. errors or 0-sized allocation). How do you face this issue?

I noticed that many programmers check the return value and manage error routines for it, while other just assert() the return value not to be NULL.

Also in C++ by the way you use the new operator without taking care about the return value (I guess it's asserted to be not NULL under the hood, is it?)

What is your opinion?

Name: Anonymous 2010-06-28 22:10

from my common.h:
/*
  new_malloc: addition to regular malloc that
  reports and error and exits whenever malloc
  returns a NULL pointer.
*/

static inline void *new_malloc (size_t alloc_size)
{
  void *temp_pointer;

  temp_pointer = GC_malloc (alloc_size);

  if (temp_pointer == NULL)
    {
      fprintf (stderr, "Could not allocate block of size %d, exiting.\n", alloc_size);
      exit (EXIT_FAILURE);
    }

  return temp_pointer;
}

/*
  new_realloc: like new_malloc except exits and
  reports when realloc returns returns a null
  pointer.
*/

static inline void *new_realloc (void *to_resize, size_t alloc_size)
{
  void *temp_pointer;

  temp_pointer = GC_realloc (to_resize, alloc_size);

  if (temp_pointer == NULL)
    {
      fprintf (stderr, "Could not allocate block of size %d, exiting.\n", alloc_size);
      exit (EXIT_FAILURE);
    }

  return temp_pointer;
}

/*
  macros to replace all mallocs with new_malloc
  and all reallocs with new_realloc.
*/

#define malloc(alloc_size) new_malloc (alloc_size)
#define realloc(to_resize, new_size) new_realloc (to_resize, new_size)
#define free(to_free) GC_free (to_free)

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List