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/.
40 #include "gbacktrace.h"
41 #include "gtestutils.h"
43 #include "glib_trace.h"
44 #include "glib-ctor.h"
47 #define MEM_PROFILE_TABLE_SIZE 4096
51 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
53 * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
54 * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
55 * match the corresponding GLib prototypes, keep configure.ac and gmem.h in sync here.
56 * g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
59 #ifdef ENABLE_GC_FRIENDLY_DEFAULT
60 gboolean g_mem_gc_friendly = TRUE;
65 * This variable is %TRUE if the <envar>G_DEBUG</envar> environment variable
66 * includes the key <link linkend="G_DEBUG">gc-friendly</link>.
68 gboolean g_mem_gc_friendly = FALSE;
71 GLIB_CTOR (g_mem_init_nomessage)
75 const GDebugKey keys[] = {
80 /* don't use g_malloc/g_message here */
81 val = _g_getenv_nomalloc ("G_DEBUG", buffer);
82 flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
83 if (flags & 1) /* gc-friendly */
85 g_mem_gc_friendly = TRUE;
89 /* --- malloc wrappers --- */
90 #ifndef REALLOC_0_WORKS
92 standard_realloc (gpointer mem,
96 return malloc (n_bytes);
98 return realloc (mem, n_bytes);
100 #endif /* !REALLOC_0_WORKS */
102 #ifdef SANE_MALLOC_PROTOS
103 # define standard_malloc malloc
104 # ifdef REALLOC_0_WORKS
105 # define standard_realloc realloc
106 # endif /* REALLOC_0_WORKS */
107 # define standard_free free
108 # define standard_calloc calloc
109 # define standard_try_malloc malloc
110 # define standard_try_realloc realloc
111 #else /* !SANE_MALLOC_PROTOS */
113 standard_malloc (gsize n_bytes)
115 return malloc (n_bytes);
117 # ifdef REALLOC_0_WORKS
119 standard_realloc (gpointer mem,
122 return realloc (mem, n_bytes);
124 # endif /* REALLOC_0_WORKS */
126 standard_free (gpointer mem)
131 standard_calloc (gsize n_blocks,
134 return calloc (n_blocks, n_bytes);
136 #define standard_try_malloc standard_malloc
137 #define standard_try_realloc standard_realloc
138 #endif /* !SANE_MALLOC_PROTOS */
141 /* --- variables --- */
142 static GMemVTable glib_mem_vtable = {
148 standard_try_realloc,
153 * @Short_Description: general memory-handling
154 * @Title: Memory Allocation
156 * These functions provide support for allocating and freeing memory.
159 * If any call to allocate memory fails, the application is terminated.
160 * This also means that there is no need to check if the call succeeded.
164 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
165 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
166 * bad things can happen, since these allocators may use different memory
167 * pools (and new/delete call constructors and destructors). See also
168 * g_mem_set_vtable().
172 /* --- functions --- */
175 * @n_bytes: the number of bytes to allocate
177 * Allocates @n_bytes bytes of memory.
178 * If @n_bytes is 0 it returns %NULL.
180 * Returns: a pointer to the allocated memory
183 g_malloc (gsize n_bytes)
185 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
187 if (G_LIKELY (n_bytes))
191 mem = glib_mem_vtable.malloc (n_bytes);
192 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
196 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
200 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
207 * @n_bytes: the number of bytes to allocate
209 * Allocates @n_bytes bytes of memory, initialized to 0's.
210 * If @n_bytes is 0 it returns %NULL.
212 * Returns: a pointer to the allocated memory
215 g_malloc0 (gsize n_bytes)
217 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
219 if (G_LIKELY (n_bytes))
223 mem = glib_mem_vtable.calloc (1, n_bytes);
224 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
228 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
232 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
239 * @mem: the memory to reallocate
240 * @n_bytes: new size of the memory in bytes
242 * Reallocates the memory pointed to by @mem, so that it now has space for
243 * @n_bytes bytes of memory. It returns the new address of the memory, which may
244 * have been moved. @mem may be %NULL, in which case it's considered to
245 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
246 * and @mem will be freed unless it is %NULL.
248 * Returns: the new address of the allocated memory
251 g_realloc (gpointer mem,
256 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
258 if (G_LIKELY (n_bytes))
260 newmem = glib_mem_vtable.realloc (mem, n_bytes);
261 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
265 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
270 glib_mem_vtable.free (mem);
272 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
279 * @mem: the memory to free
281 * Frees the memory pointed to by @mem.
282 * If @mem is %NULL it simply returns.
285 g_free (gpointer mem)
287 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
290 glib_mem_vtable.free (mem);
291 TRACE(GLIB_MEM_FREE((void*) mem));
296 * @n_bytes: number of bytes to allocate.
298 * Attempts to allocate @n_bytes, and returns %NULL on failure.
299 * Contrast with g_malloc(), which aborts the program on failure.
301 * Returns: the allocated memory, or %NULL.
304 g_try_malloc (gsize n_bytes)
308 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
310 if (G_LIKELY (n_bytes))
311 mem = glib_mem_vtable.try_malloc (n_bytes);
315 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
322 * @n_bytes: number of bytes to allocate
324 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
325 * failure. Contrast with g_malloc0(), which aborts the program on failure.
328 * Returns: the allocated memory, or %NULL
331 g_try_malloc0 (gsize n_bytes)
335 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
337 if (G_LIKELY (n_bytes))
338 mem = glib_mem_vtable.try_malloc (n_bytes);
343 memset (mem, 0, n_bytes);
350 * @mem: previously-allocated memory, or %NULL.
351 * @n_bytes: number of bytes to allocate.
353 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
354 * on failure. Contrast with g_realloc(), which aborts the program
355 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
357 * Returns: the allocated memory, or %NULL.
360 g_try_realloc (gpointer mem,
365 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
367 if (G_LIKELY (n_bytes))
368 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
373 glib_mem_vtable.free (mem);
376 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
382 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
386 * @n_blocks: the number of blocks to allocate
387 * @n_block_bytes: the size of each block in bytes
389 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
390 * but care is taken to detect possible overflow during multiplication.
393 * Returns: a pointer to the allocated memory
396 g_malloc_n (gsize n_blocks,
399 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
401 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
403 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
404 G_STRLOC, n_blocks, n_block_bytes);
407 return g_malloc (n_blocks * n_block_bytes);
412 * @n_blocks: the number of blocks to allocate
413 * @n_block_bytes: the size of each block in bytes
415 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
416 * but care is taken to detect possible overflow during multiplication.
419 * Returns: a pointer to the allocated memory
422 g_malloc0_n (gsize n_blocks,
425 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
427 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
429 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
430 G_STRLOC, n_blocks, n_block_bytes);
433 return g_malloc0 (n_blocks * n_block_bytes);
438 * @mem: the memory to reallocate
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_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
443 * but care is taken to detect possible overflow during multiplication.
446 * Returns: the new address of the allocated memory
449 g_realloc_n (gpointer mem,
453 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
455 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
457 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
458 G_STRLOC, n_blocks, n_block_bytes);
461 return g_realloc (mem, n_blocks * n_block_bytes);
466 * @n_blocks: the number of blocks to allocate
467 * @n_block_bytes: the size of each block in bytes
469 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
470 * but care is taken to detect possible overflow during multiplication.
473 * Returns: the allocated memory, or %NULL.
476 g_try_malloc_n (gsize n_blocks,
479 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
482 return g_try_malloc (n_blocks * n_block_bytes);
487 * @n_blocks: the number of blocks to allocate
488 * @n_block_bytes: the size of each block in bytes
490 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
491 * but care is taken to detect possible overflow during multiplication.
494 * Returns: the allocated memory, or %NULL
497 g_try_malloc0_n (gsize n_blocks,
500 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
503 return g_try_malloc0 (n_blocks * n_block_bytes);
508 * @mem: previously-allocated memory, or %NULL.
509 * @n_blocks: the number of blocks to allocate
510 * @n_block_bytes: the size of each block in bytes
512 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
513 * but care is taken to detect possible overflow during multiplication.
516 * Returns: the allocated memory, or %NULL.
519 g_try_realloc_n (gpointer mem,
523 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
526 return g_try_realloc (mem, n_blocks * n_block_bytes);
532 fallback_calloc (gsize n_blocks,
535 gsize l = n_blocks * n_block_bytes;
536 gpointer mem = glib_mem_vtable.malloc (l);
544 static gboolean vtable_set = FALSE;
547 * g_mem_is_system_malloc
549 * Checks whether the allocator used by g_malloc() is the system's
550 * malloc implementation. If it returns %TRUE memory allocated with
551 * malloc() can be used interchangeable with memory allocated using g_malloc().
552 * This function is useful for avoiding an extra copy of allocated memory returned
553 * by a non-GLib-based API.
555 * A different allocator can be set using g_mem_set_vtable().
557 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
560 g_mem_is_system_malloc (void)
567 * @vtable: table of memory allocation routines.
569 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
570 * custom memory allocation routines. <emphasis>This function must be called
571 * before using any other GLib functions.</emphasis> The @vtable only needs to
572 * provide malloc(), realloc(), and free() functions; GLib can provide default
573 * implementations of the others. The malloc() and realloc() implementations
574 * should return %NULL on failure, GLib will handle error-checking for you.
575 * @vtable is copied, so need not persist after this function has been called.
578 g_mem_set_vtable (GMemVTable *vtable)
582 if (vtable->malloc && vtable->realloc && vtable->free)
584 glib_mem_vtable.malloc = vtable->malloc;
585 glib_mem_vtable.realloc = vtable->realloc;
586 glib_mem_vtable.free = vtable->free;
587 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
588 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
589 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
593 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
596 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
600 /* --- memory profiling and checking --- */
601 #ifdef G_DISABLE_CHECKS
603 * glib_mem_profiler_table:
605 * A #GMemVTable containing profiling variants of the memory
606 * allocation functions. Use them together with g_mem_profile()
607 * in order to get information about the memory allocation pattern
610 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
615 #else /* !G_DISABLE_CHECKS */
622 static guint *profile_data = NULL;
623 static gsize profile_allocs = 0;
624 static gsize profile_zinit = 0;
625 static gsize profile_frees = 0;
626 static GMutex gmem_profile_mutex;
627 #ifdef G_ENABLE_DEBUG
628 static volatile gsize g_trap_free_size = 0;
629 static volatile gsize g_trap_realloc_size = 0;
630 static volatile gsize g_trap_malloc_size = 0;
631 #endif /* G_ENABLE_DEBUG */
633 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
636 profiler_log (ProfilerJob job,
640 g_mutex_lock (&gmem_profile_mutex);
643 profile_data = standard_calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
644 sizeof (profile_data[0]));
645 if (!profile_data) /* memory system kiddin' me, eh? */
647 g_mutex_unlock (&gmem_profile_mutex);
652 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
653 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
654 (job & PROFILER_RELOC) != 0,
657 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
658 (job & PROFILER_RELOC) != 0,
662 if (job & PROFILER_ALLOC)
664 profile_allocs += n_bytes;
665 if (job & PROFILER_ZINIT)
666 profile_zinit += n_bytes;
669 profile_frees += n_bytes;
671 g_mutex_unlock (&gmem_profile_mutex);
675 profile_print_locked (guint *local_data,
678 gboolean need_header = TRUE;
681 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
683 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
684 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
685 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
686 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
688 if (!t_malloc && !t_realloc && !t_free && !t_refree)
690 else if (need_header)
693 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
694 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
695 g_print (" | malloc() | free() | realloc() | realloc() | \n");
696 g_print ("===========|============|============|============|============|===========\n");
698 if (i < MEM_PROFILE_TABLE_SIZE)
699 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
700 i, t_malloc, t_free, t_realloc, t_refree,
701 (t_malloc - t_free + t_realloc - t_refree) * i);
702 else if (i >= MEM_PROFILE_TABLE_SIZE)
703 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
704 i, t_malloc, t_free, t_realloc, t_refree);
707 g_print (" --- none ---\n");
714 * Outputs a summary of memory usage.
716 * It outputs the frequency of allocations of different sizes,
717 * the total number of bytes which have been allocated,
718 * the total number of bytes which have been freed,
719 * and the difference between the previous two values, i.e. the number of bytes
722 * Note that this function will not output anything unless you have
723 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
729 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
734 GLIB_ENSURE_CTOR (g_mem_init_nomessage);
736 g_mutex_lock (&gmem_profile_mutex);
738 local_allocs = profile_allocs;
739 local_zinit = profile_zinit;
740 local_frees = profile_frees;
744 g_mutex_unlock (&gmem_profile_mutex);
748 memcpy (local_data, profile_data,
749 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
751 g_mutex_unlock (&gmem_profile_mutex);
753 g_print ("GLib Memory statistics (successful operations):\n");
754 profile_print_locked (local_data, TRUE);
755 g_print ("GLib Memory statistics (failing operations):\n");
756 profile_print_locked (local_data, FALSE);
757 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
758 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
759 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
760 "remaining=%"G_GSIZE_FORMAT"\n",
763 ((gdouble) local_zinit) / local_allocs * 100.0,
765 ((gdouble) local_frees) / local_allocs * 100.0,
766 local_allocs - local_frees);
770 profiler_try_malloc (gsize n_bytes)
774 #ifdef G_ENABLE_DEBUG
775 if (g_trap_malloc_size == n_bytes)
777 #endif /* G_ENABLE_DEBUG */
779 p = standard_malloc (sizeof (gsize) * 2 + n_bytes);
783 p[0] = 0; /* free count */
784 p[1] = n_bytes; /* length */
785 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
789 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
795 profiler_malloc (gsize n_bytes)
797 gpointer mem = profiler_try_malloc (n_bytes);
806 profiler_calloc (gsize n_blocks,
809 gsize l = n_blocks * n_block_bytes;
812 #ifdef G_ENABLE_DEBUG
813 if (g_trap_malloc_size == l)
815 #endif /* G_ENABLE_DEBUG */
817 p = standard_calloc (1, sizeof (gsize) * 2 + l);
821 p[0] = 0; /* free count */
822 p[1] = l; /* length */
823 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
828 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
836 profiler_free (gpointer mem)
841 if (p[0]) /* free count */
843 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
845 profiler_log (PROFILER_FREE,
851 #ifdef G_ENABLE_DEBUG
852 if (g_trap_free_size == p[1])
854 #endif /* G_ENABLE_DEBUG */
856 profiler_log (PROFILER_FREE,
859 memset (p + 2, 0xaa, p[1]);
861 /* for all those that miss standard_free (p); in this place, yes,
862 * we do leak all memory when profiling, and that is intentional
863 * to catch double frees. patch submissions are futile.
870 profiler_try_realloc (gpointer mem,
877 #ifdef G_ENABLE_DEBUG
878 if (g_trap_realloc_size == n_bytes)
880 #endif /* G_ENABLE_DEBUG */
882 if (mem && p[0]) /* free count */
884 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
885 "memory has been freed %"G_GSIZE_FORMAT" times already",
886 p + 2, (gsize) n_bytes, p[0]);
887 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
893 p = standard_realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
898 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
901 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
905 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
912 profiler_realloc (gpointer mem,
915 mem = profiler_try_realloc (mem, n_bytes);
923 static GMemVTable profiler_table = {
929 profiler_try_realloc,
931 GMemVTable *glib_mem_profiler_table = &profiler_table;
933 #endif /* !G_DISABLE_CHECKS */