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 {
00027 namespace memory
00028 {
00029 /*
00030   Malloc many pointers at the same time
00031   Only ptr1 can be free'd, and doing this will free all
00032   the memory allocated. ptr2, etc all point inside big allocated
00033   memory area.
00034 
00035   SYNOPSIS
00036     multi_malloc()
00037       zerofill             Whether or not to fill with 0
00038   ptr1, length1      Multiple arguments terminated by null ptr
00039   ptr2, length2      ...
00040         ...
00041   NULL
00042 */
00043 
00044 void* multi_malloc(bool zerofill, ...)
00045 {
00046   va_list args;
00047   void **ptr, *start;
00048   char *res;
00049   size_t tot_length,length;
00050 
00051   va_start(args, zerofill);
00052   tot_length=0;
00053   while ((ptr=va_arg(args, void **)))
00054   {
00055     /*
00056      * This must be unsigned int, not size_t.
00057      * Otherwise, everything breaks.
00058      */
00059     length=va_arg(args, unsigned int);
00060     tot_length+=ALIGN_SIZE(length);
00061   }
00062   va_end(args);
00063 
00064 #ifdef HAVE_VALGRIND
00065   if (!(start= calloc(0, tot_length)))
00066     return(0);
00067 #else
00068   if (!(start= malloc(tot_length)))
00069     return(0);
00070   if (zerofill)
00071     memset(start, 0, tot_length);
00072 #endif
00073 
00074   va_start(args, zerofill);
00075   res= static_cast<char *>(start);
00076   while ((ptr=va_arg(args, void **)))
00077   {
00078     *ptr=res;
00079     length=va_arg(args,unsigned int);
00080     res+= ALIGN_SIZE(length);
00081   }
00082   va_end(args);
00083   return start;
00084 }
00085 
00086 } /* namespace memory */
00087 } /* namespace drizzled */