2015年5月14日 星期四

[C] How to use xmalloc and xrealloc


#include <stdio.h> /* for printf */
#include <stdlib.h>
#include <malloc.h>

void *
xmalloc (unsigned int size)
{
  /* Make sure we don't allocate 0, for pre-ISO implementations.  */
  void *result = malloc (size ? size : 1);
  if (result == 0)
     printf("virtual memory exhausted \n"); 
  return result;
}

void *
xrealloc (void *ptr, unsigned int size)
{
  void *result;

  /* Some older implementations of realloc() don't conform to ISO.  */
  if (! size)
    size = 1;
  result = ptr ? realloc (ptr, size) : malloc (size);
  if (result == 0)
     printf("virtual memory exhausted \n"); 

  return result;
}


void tst_realloc (void) {
  char *p;
  char *new_p;

  p = xmalloc (2);

  if (p != NULL) {
    new_p = xrealloc (p, 4);

    if (new_p != NULL)
      p = new_p;
    else
      printf ("Reallocation failed\n");
  }
}

int main(void)
{
   tst_realloc();

   return 0;
}
Reference:
- GNU Make Version 3.81

0 意見:

張貼留言