Drizzled Public API Documentation

multi_malloc.cc
00001 /* Copyright (C) 2000 MySQL AB
00002 
00003    This program is free software; you can redistribute it and/or modify
00004    it under the terms of the GNU General Public License as published by
00005    the Free Software Foundation; version 2 of the License.
00006 
00007    This program is distributed in the hope that it will be useful,
00008    but WITHOUT ANY WARRANTY; without even the implied warranty of
00009    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00010    GNU General Public License for more details.
00011 
00012    You should have received a copy of the GNU General Public License
00013    along with this program; if not, write to the Free Software
00014    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
00015 
00016 #include <config.h>
00017 
00018 #include <stdarg.h>
00019 #include <string.h>
00020 #include <stdlib.h>
00021 
00022 #include <drizzled/memory/multi_malloc.h>
00023 #include <drizzled/definitions.h>
00024 
00025 namespace drizzled {
00026 namespace memory {
00027 
00028 /*
00029   Malloc many pointers at the same time
00030   Only ptr1 can be free'd, and doing this will free all
00031   the memory allocated. ptr2, etc all point inside big allocated
00032   memory area.
00033 
00034   SYNOPSIS
00035     multi_malloc()
00036       zerofill             Whether or not to fill with 0
00037   ptr1, length1      Multiple arguments terminated by null ptr
00038   ptr2, length2      ...
00039         ...
00040   NULL
00041 */
00042 
00043 void* multi_malloc(bool zerofill, ...)
00044 {
00045   va_list args;
00046   void **ptr, *start;
00047   char *res;
00048   size_t tot_length,length;
00049 
00050   va_start(args, zerofill);
00051   tot_length=0;
00052   while ((ptr=va_arg(args, void **)))
00053   {
00054     /*
00055      * This must be unsigned int, not size_t.
00056      * Otherwise, everything breaks.
00057      */
00058     length=va_arg(args, unsigned int);
00059     tot_length+=ALIGN_SIZE(length);
00060   }
00061   va_end(args);
00062 
00063 #ifdef HAVE_VALGRIND
00064   if (!(start= calloc(0, tot_length)))
00065     return 0;
00066 #else
00067   start= malloc(tot_length);
00068   if (zerofill)
00069     memset(start, 0, tot_length);
00070 #endif
00071 
00072   va_start(args, zerofill);
00073   res= static_cast<char *>(start);
00074   while ((ptr=va_arg(args, void **)))
00075   {
00076     *ptr=res;
00077     length=va_arg(args,unsigned int);
00078     res+= ALIGN_SIZE(length);
00079   }
00080   va_end(args);
00081   return start;
00082 }
00083 
00084 } /* namespace memory */
00085 } /* namespace drizzled */