What is the difference between xmalloc and malloc?

前端 未结 6 1172
萌比男神i
萌比男神i 2021-01-31 13:57

What is the difference between xmalloc() and malloc() for memory allocation?
Is there any pro of using xmalloc()?

6条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 14:54

    an primitive example of xmalloc.c in K&R C

    #include 
    extern char *malloc ();
    void *
    xmalloc (size)
        unsigned size;
    {
      void *new_mem = (void *) malloc (size);
      if (new_mem == NULL)    
        {
          fprintf (stderr, "fatal: memory exhausted (xmalloc of %u bytes).\n", size);
          exit (-1);
        }
      return new_mem;
    }
    

    then in your code header (early) you put

    #define malloc(m) xmalloc(m)

    to silently rewrite the source before compilation. (you can see the rewritten code by invoking the C preprocessor directly and saving the output. )

    if crashing your program is not what you want you can do something different

    • Use a garbage collector
    • redesign your code to be less of a memory hog
    • have error checking code in your program to handle an Out of Memory or other allocation error gracefully.

    Users don't enjoy losing their data to a built-in crash command in their program.

提交回复
热议问题