1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
39 #include "glib-init.h"
42 #include "gbacktrace.h"
43 #include "gtestutils.h"
45 #include "glib_trace.h"
46 #include "glib-ctor.h"
49 #define MEM_PROFILE_TABLE_SIZE 4096
53 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
55 * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
56 * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
57 * match the corresponding GLib prototypes, keep configure.ac and gmem.h in sync here.
58 * g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
61 /* --- malloc wrappers --- */
62 #ifndef REALLOC_0_WORKS
64 standard_realloc (gpointer mem,
68 return malloc (n_bytes);
70 return realloc (mem, n_bytes);
72 #endif /* !REALLOC_0_WORKS */
74 #ifdef SANE_MALLOC_PROTOS
75 # define standard_malloc malloc
76 # ifdef REALLOC_0_WORKS
77 # define standard_realloc realloc
78 # endif /* REALLOC_0_WORKS */
79 # define standard_free free
80 # define standard_calloc calloc
81 # define standard_try_malloc malloc
82 # define standard_try_realloc realloc
83 #else /* !SANE_MALLOC_PROTOS */
85 standard_malloc (gsize n_bytes)
87 return malloc (n_bytes);
89 # ifdef REALLOC_0_WORKS
91 standard_realloc (gpointer mem,
94 return realloc (mem, n_bytes);
96 # endif /* REALLOC_0_WORKS */
98 standard_free (gpointer mem)
103 standard_calloc (gsize n_blocks,
106 return calloc (n_blocks, n_bytes);
108 #define standard_try_malloc standard_malloc
109 #define standard_try_realloc standard_realloc
110 #endif /* !SANE_MALLOC_PROTOS */
113 /* --- variables --- */
114 static GMemVTable glib_mem_vtable = {
120 standard_try_realloc,
125 * @Short_Description: general memory-handling
126 * @Title: Memory Allocation
128 * These functions provide support for allocating and freeing memory.
131 * If any call to allocate memory fails, the application is terminated.
132 * This also means that there is no need to check if the call succeeded.
136 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
137 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
138 * bad things can happen, since these allocators may use different memory
139 * pools (and new/delete call constructors and destructors). See also
140 * g_mem_set_vtable().
144 /* --- functions --- */
147 * @n_bytes: the number of bytes to allocate
149 * Allocates @n_bytes bytes of memory.
150 * If @n_bytes is 0 it returns %NULL.
152 * Returns: a pointer to the allocated memory
155 g_malloc (gsize n_bytes)
157 if (G_LIKELY (n_bytes))
161 mem = glib_mem_vtable.malloc (n_bytes);
162 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
166 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
170 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
177 * @n_bytes: the number of bytes to allocate
179 * Allocates @n_bytes bytes of memory, initialized to 0's.
180 * If @n_bytes is 0 it returns %NULL.
182 * Returns: a pointer to the allocated memory
185 g_malloc0 (gsize n_bytes)
187 if (G_LIKELY (n_bytes))
191 mem = glib_mem_vtable.calloc (1, n_bytes);
192 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
196 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
200 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
207 * @mem: the memory to reallocate
208 * @n_bytes: new size of the memory in bytes
210 * Reallocates the memory pointed to by @mem, so that it now has space for
211 * @n_bytes bytes of memory. It returns the new address of the memory, which may
212 * have been moved. @mem may be %NULL, in which case it's considered to
213 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
214 * and @mem will be freed unless it is %NULL.
216 * Returns: the new address of the allocated memory
219 g_realloc (gpointer mem,
224 if (G_LIKELY (n_bytes))
226 newmem = glib_mem_vtable.realloc (mem, n_bytes);
227 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
231 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
236 glib_mem_vtable.free (mem);
238 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
245 * @mem: the memory to free
247 * Frees the memory pointed to by @mem.
248 * If @mem is %NULL it simply returns.
251 g_free (gpointer mem)
254 glib_mem_vtable.free (mem);
255 TRACE(GLIB_MEM_FREE((void*) mem));
260 * @n_bytes: number of bytes to allocate.
262 * Attempts to allocate @n_bytes, and returns %NULL on failure.
263 * Contrast with g_malloc(), which aborts the program on failure.
265 * Returns: the allocated memory, or %NULL.
268 g_try_malloc (gsize n_bytes)
272 if (G_LIKELY (n_bytes))
273 mem = glib_mem_vtable.try_malloc (n_bytes);
277 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
284 * @n_bytes: number of bytes to allocate
286 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
287 * failure. Contrast with g_malloc0(), which aborts the program on failure.
290 * Returns: the allocated memory, or %NULL
293 g_try_malloc0 (gsize n_bytes)
297 if (G_LIKELY (n_bytes))
298 mem = glib_mem_vtable.try_malloc (n_bytes);
303 memset (mem, 0, n_bytes);
310 * @mem: previously-allocated memory, or %NULL.
311 * @n_bytes: number of bytes to allocate.
313 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
314 * on failure. Contrast with g_realloc(), which aborts the program
315 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
317 * Returns: the allocated memory, or %NULL.
320 g_try_realloc (gpointer mem,
325 if (G_LIKELY (n_bytes))
326 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
331 glib_mem_vtable.free (mem);
334 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
340 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
344 * @n_blocks: the number of blocks to allocate
345 * @n_block_bytes: the size of each block in bytes
347 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
348 * but care is taken to detect possible overflow during multiplication.
351 * Returns: a pointer to the allocated memory
354 g_malloc_n (gsize n_blocks,
357 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
359 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
360 G_STRLOC, n_blocks, n_block_bytes);
363 return g_malloc (n_blocks * n_block_bytes);
368 * @n_blocks: the number of blocks to allocate
369 * @n_block_bytes: the size of each block in bytes
371 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
372 * but care is taken to detect possible overflow during multiplication.
375 * Returns: a pointer to the allocated memory
378 g_malloc0_n (gsize n_blocks,
381 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
383 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
384 G_STRLOC, n_blocks, n_block_bytes);
387 return g_malloc0 (n_blocks * n_block_bytes);
392 * @mem: the memory to reallocate
393 * @n_blocks: the number of blocks to allocate
394 * @n_block_bytes: the size of each block in bytes
396 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
397 * but care is taken to detect possible overflow during multiplication.
400 * Returns: the new address of the allocated memory
403 g_realloc_n (gpointer mem,
407 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
409 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
410 G_STRLOC, n_blocks, n_block_bytes);
413 return g_realloc (mem, n_blocks * n_block_bytes);
418 * @n_blocks: the number of blocks to allocate
419 * @n_block_bytes: the size of each block in bytes
421 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
422 * but care is taken to detect possible overflow during multiplication.
425 * Returns: the allocated memory, or %NULL.
428 g_try_malloc_n (gsize n_blocks,
431 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
434 return g_try_malloc (n_blocks * n_block_bytes);
439 * @n_blocks: the number of blocks to allocate
440 * @n_block_bytes: the size of each block in bytes
442 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
443 * but care is taken to detect possible overflow during multiplication.
446 * Returns: the allocated memory, or %NULL
449 g_try_malloc0_n (gsize n_blocks,
452 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
455 return g_try_malloc0 (n_blocks * n_block_bytes);
460 * @mem: previously-allocated memory, or %NULL.
461 * @n_blocks: the number of blocks to allocate
462 * @n_block_bytes: the size of each block in bytes
464 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
465 * but care is taken to detect possible overflow during multiplication.
468 * Returns: the allocated memory, or %NULL.
471 g_try_realloc_n (gpointer mem,
475 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
478 return g_try_realloc (mem, n_blocks * n_block_bytes);
484 fallback_calloc (gsize n_blocks,
487 gsize l = n_blocks * n_block_bytes;
488 gpointer mem = glib_mem_vtable.malloc (l);
496 static gboolean vtable_set = FALSE;
499 * g_mem_is_system_malloc
501 * Checks whether the allocator used by g_malloc() is the system's
502 * malloc implementation. If it returns %TRUE memory allocated with
503 * malloc() can be used interchangeable with memory allocated using g_malloc().
504 * This function is useful for avoiding an extra copy of allocated memory returned
505 * by a non-GLib-based API.
507 * A different allocator can be set using g_mem_set_vtable().
509 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
512 g_mem_is_system_malloc (void)
519 * @vtable: table of memory allocation routines.
521 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
522 * custom memory allocation routines. <emphasis>This function must be called
523 * before using any other GLib functions.</emphasis> The @vtable only needs to
524 * provide malloc(), realloc(), and free() functions; GLib can provide default
525 * implementations of the others. The malloc() and realloc() implementations
526 * should return %NULL on failure, GLib will handle error-checking for you.
527 * @vtable is copied, so need not persist after this function has been called.
530 g_mem_set_vtable (GMemVTable *vtable)
534 if (vtable->malloc && vtable->realloc && vtable->free)
536 glib_mem_vtable.malloc = vtable->malloc;
537 glib_mem_vtable.realloc = vtable->realloc;
538 glib_mem_vtable.free = vtable->free;
539 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
540 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
541 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
545 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
548 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
552 /* --- memory profiling and checking --- */
553 #ifdef G_DISABLE_CHECKS
555 * glib_mem_profiler_table:
557 * A #GMemVTable containing profiling variants of the memory
558 * allocation functions. Use them together with g_mem_profile()
559 * in order to get information about the memory allocation pattern
562 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
567 #else /* !G_DISABLE_CHECKS */
574 static guint *profile_data = NULL;
575 static gsize profile_allocs = 0;
576 static gsize profile_zinit = 0;
577 static gsize profile_frees = 0;
578 static GMutex gmem_profile_mutex;
579 #ifdef G_ENABLE_DEBUG
580 static volatile gsize g_trap_free_size = 0;
581 static volatile gsize g_trap_realloc_size = 0;
582 static volatile gsize g_trap_malloc_size = 0;
583 #endif /* G_ENABLE_DEBUG */
585 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
588 profiler_log (ProfilerJob job,
592 g_mutex_lock (&gmem_profile_mutex);
595 profile_data = standard_calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
596 sizeof (profile_data[0]));
597 if (!profile_data) /* memory system kiddin' me, eh? */
599 g_mutex_unlock (&gmem_profile_mutex);
604 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
605 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
606 (job & PROFILER_RELOC) != 0,
609 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
610 (job & PROFILER_RELOC) != 0,
614 if (job & PROFILER_ALLOC)
616 profile_allocs += n_bytes;
617 if (job & PROFILER_ZINIT)
618 profile_zinit += n_bytes;
621 profile_frees += n_bytes;
623 g_mutex_unlock (&gmem_profile_mutex);
627 profile_print_locked (guint *local_data,
630 gboolean need_header = TRUE;
633 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
635 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
636 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
637 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
638 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
640 if (!t_malloc && !t_realloc && !t_free && !t_refree)
642 else if (need_header)
645 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
646 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
647 g_print (" | malloc() | free() | realloc() | realloc() | \n");
648 g_print ("===========|============|============|============|============|===========\n");
650 if (i < MEM_PROFILE_TABLE_SIZE)
651 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
652 i, t_malloc, t_free, t_realloc, t_refree,
653 (t_malloc - t_free + t_realloc - t_refree) * i);
654 else if (i >= MEM_PROFILE_TABLE_SIZE)
655 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
656 i, t_malloc, t_free, t_realloc, t_refree);
659 g_print (" --- none ---\n");
666 * Outputs a summary of memory usage.
668 * It outputs the frequency of allocations of different sizes,
669 * the total number of bytes which have been allocated,
670 * the total number of bytes which have been freed,
671 * and the difference between the previous two values, i.e. the number of bytes
674 * Note that this function will not output anything unless you have
675 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
681 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
686 g_mutex_lock (&gmem_profile_mutex);
688 local_allocs = profile_allocs;
689 local_zinit = profile_zinit;
690 local_frees = profile_frees;
694 g_mutex_unlock (&gmem_profile_mutex);
698 memcpy (local_data, profile_data,
699 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
701 g_mutex_unlock (&gmem_profile_mutex);
703 g_print ("GLib Memory statistics (successful operations):\n");
704 profile_print_locked (local_data, TRUE);
705 g_print ("GLib Memory statistics (failing operations):\n");
706 profile_print_locked (local_data, FALSE);
707 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
708 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
709 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
710 "remaining=%"G_GSIZE_FORMAT"\n",
713 ((gdouble) local_zinit) / local_allocs * 100.0,
715 ((gdouble) local_frees) / local_allocs * 100.0,
716 local_allocs - local_frees);
720 profiler_try_malloc (gsize n_bytes)
724 #ifdef G_ENABLE_DEBUG
725 if (g_trap_malloc_size == n_bytes)
727 #endif /* G_ENABLE_DEBUG */
729 p = standard_malloc (sizeof (gsize) * 2 + n_bytes);
733 p[0] = 0; /* free count */
734 p[1] = n_bytes; /* length */
735 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
739 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
745 profiler_malloc (gsize n_bytes)
747 gpointer mem = profiler_try_malloc (n_bytes);
756 profiler_calloc (gsize n_blocks,
759 gsize l = n_blocks * n_block_bytes;
762 #ifdef G_ENABLE_DEBUG
763 if (g_trap_malloc_size == l)
765 #endif /* G_ENABLE_DEBUG */
767 p = standard_calloc (1, sizeof (gsize) * 2 + l);
771 p[0] = 0; /* free count */
772 p[1] = l; /* length */
773 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
778 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
786 profiler_free (gpointer mem)
791 if (p[0]) /* free count */
793 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
795 profiler_log (PROFILER_FREE,
801 #ifdef G_ENABLE_DEBUG
802 if (g_trap_free_size == p[1])
804 #endif /* G_ENABLE_DEBUG */
806 profiler_log (PROFILER_FREE,
809 memset (p + 2, 0xaa, p[1]);
811 /* for all those that miss standard_free (p); in this place, yes,
812 * we do leak all memory when profiling, and that is intentional
813 * to catch double frees. patch submissions are futile.
820 profiler_try_realloc (gpointer mem,
827 #ifdef G_ENABLE_DEBUG
828 if (g_trap_realloc_size == n_bytes)
830 #endif /* G_ENABLE_DEBUG */
832 if (mem && p[0]) /* free count */
834 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
835 "memory has been freed %"G_GSIZE_FORMAT" times already",
836 p + 2, (gsize) n_bytes, p[0]);
837 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
843 p = standard_realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
848 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
851 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
855 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
862 profiler_realloc (gpointer mem,
865 mem = profiler_try_realloc (mem, n_bytes);
873 static GMemVTable profiler_table = {
879 profiler_try_realloc,
881 GMemVTable *glib_mem_profiler_table = &profiler_table;
883 #endif /* !G_DISABLE_CHECKS */