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"
46 #define MEM_PROFILE_TABLE_SIZE 4096
50 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
52 * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
53 * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
54 * match the corresponding GLib prototypes, keep configure.ac and gmem.h in sync here.
55 * g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
58 /* --- prototypes --- */
59 static gboolean g_mem_initialized = FALSE;
60 static void g_mem_init_nomessage (void);
63 /* --- malloc wrappers --- */
64 #ifndef REALLOC_0_WORKS
66 standard_realloc (gpointer mem,
70 return malloc (n_bytes);
72 return realloc (mem, n_bytes);
74 #endif /* !REALLOC_0_WORKS */
76 #ifdef SANE_MALLOC_PROTOS
77 # define standard_malloc malloc
78 # ifdef REALLOC_0_WORKS
79 # define standard_realloc realloc
80 # endif /* REALLOC_0_WORKS */
81 # define standard_free free
82 # define standard_calloc calloc
83 # define standard_try_malloc malloc
84 # define standard_try_realloc realloc
85 #else /* !SANE_MALLOC_PROTOS */
87 standard_malloc (gsize n_bytes)
89 return malloc (n_bytes);
91 # ifdef REALLOC_0_WORKS
93 standard_realloc (gpointer mem,
96 return realloc (mem, n_bytes);
98 # endif /* REALLOC_0_WORKS */
100 standard_free (gpointer mem)
105 standard_calloc (gsize n_blocks,
108 return calloc (n_blocks, n_bytes);
110 #define standard_try_malloc standard_malloc
111 #define standard_try_realloc standard_realloc
112 #endif /* !SANE_MALLOC_PROTOS */
115 /* --- variables --- */
116 static GMemVTable glib_mem_vtable = {
122 standard_try_realloc,
127 * @Short_Description: general memory-handling
128 * @Title: Memory Allocation
130 * These functions provide support for allocating and freeing memory.
133 * If any call to allocate memory fails, the application is terminated.
134 * This also means that there is no need to check if the call succeeded.
138 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
139 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
140 * bad things can happen, since these allocators may use different memory
141 * pools (and new/delete call constructors and destructors). See also
142 * g_mem_set_vtable().
146 /* --- functions --- */
149 * @n_bytes: the number of bytes to allocate
151 * Allocates @n_bytes bytes of memory.
152 * If @n_bytes is 0 it returns %NULL.
154 * Returns: a pointer to the allocated memory
157 g_malloc (gsize n_bytes)
159 if (G_UNLIKELY (!g_mem_initialized))
160 g_mem_init_nomessage();
161 if (G_LIKELY (n_bytes))
165 mem = glib_mem_vtable.malloc (n_bytes);
166 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
170 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
174 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
181 * @n_bytes: the number of bytes to allocate
183 * Allocates @n_bytes bytes of memory, initialized to 0's.
184 * If @n_bytes is 0 it returns %NULL.
186 * Returns: a pointer to the allocated memory
189 g_malloc0 (gsize n_bytes)
191 if (G_UNLIKELY (!g_mem_initialized))
192 g_mem_init_nomessage();
193 if (G_LIKELY (n_bytes))
197 mem = glib_mem_vtable.calloc (1, n_bytes);
198 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
202 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
206 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
213 * @mem: the memory to reallocate
214 * @n_bytes: new size of the memory in bytes
216 * Reallocates the memory pointed to by @mem, so that it now has space for
217 * @n_bytes bytes of memory. It returns the new address of the memory, which may
218 * have been moved. @mem may be %NULL, in which case it's considered to
219 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
220 * and @mem will be freed unless it is %NULL.
222 * Returns: the new address of the allocated memory
225 g_realloc (gpointer mem,
230 if (G_UNLIKELY (!g_mem_initialized))
231 g_mem_init_nomessage();
232 if (G_LIKELY (n_bytes))
234 newmem = glib_mem_vtable.realloc (mem, n_bytes);
235 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
239 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
244 glib_mem_vtable.free (mem);
246 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
253 * @mem: the memory to free
255 * Frees the memory pointed to by @mem.
256 * If @mem is %NULL it simply returns.
259 g_free (gpointer mem)
261 if (G_UNLIKELY (!g_mem_initialized))
262 g_mem_init_nomessage();
264 glib_mem_vtable.free (mem);
265 TRACE(GLIB_MEM_FREE((void*) mem));
270 * @n_bytes: number of bytes to allocate.
272 * Attempts to allocate @n_bytes, and returns %NULL on failure.
273 * Contrast with g_malloc(), which aborts the program on failure.
275 * Returns: the allocated memory, or %NULL.
278 g_try_malloc (gsize n_bytes)
282 if (G_UNLIKELY (!g_mem_initialized))
283 g_mem_init_nomessage();
284 if (G_LIKELY (n_bytes))
285 mem = glib_mem_vtable.try_malloc (n_bytes);
289 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
296 * @n_bytes: number of bytes to allocate
298 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
299 * failure. Contrast with g_malloc0(), which aborts the program on failure.
302 * Returns: the allocated memory, or %NULL
305 g_try_malloc0 (gsize n_bytes)
309 if (G_UNLIKELY (!g_mem_initialized))
310 g_mem_init_nomessage();
311 if (G_LIKELY (n_bytes))
312 mem = glib_mem_vtable.try_malloc (n_bytes);
317 memset (mem, 0, n_bytes);
324 * @mem: previously-allocated memory, or %NULL.
325 * @n_bytes: number of bytes to allocate.
327 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
328 * on failure. Contrast with g_realloc(), which aborts the program
329 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
331 * Returns: the allocated memory, or %NULL.
334 g_try_realloc (gpointer mem,
339 if (G_UNLIKELY (!g_mem_initialized))
340 g_mem_init_nomessage();
341 if (G_LIKELY (n_bytes))
342 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
347 glib_mem_vtable.free (mem);
350 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
356 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
360 * @n_blocks: the number of blocks to allocate
361 * @n_block_bytes: the size of each block in bytes
363 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
364 * but care is taken to detect possible overflow during multiplication.
367 * Returns: a pointer to the allocated memory
370 g_malloc_n (gsize n_blocks,
373 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
375 if (G_UNLIKELY (!g_mem_initialized))
376 g_mem_init_nomessage();
378 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
379 G_STRLOC, n_blocks, n_block_bytes);
382 return g_malloc (n_blocks * n_block_bytes);
387 * @n_blocks: the number of blocks to allocate
388 * @n_block_bytes: the size of each block in bytes
390 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
391 * but care is taken to detect possible overflow during multiplication.
394 * Returns: a pointer to the allocated memory
397 g_malloc0_n (gsize n_blocks,
400 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
402 if (G_UNLIKELY (!g_mem_initialized))
403 g_mem_init_nomessage();
405 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
406 G_STRLOC, n_blocks, n_block_bytes);
409 return g_malloc0 (n_blocks * n_block_bytes);
414 * @mem: the memory to reallocate
415 * @n_blocks: the number of blocks to allocate
416 * @n_block_bytes: the size of each block in bytes
418 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
419 * but care is taken to detect possible overflow during multiplication.
422 * Returns: the new address of the allocated memory
425 g_realloc_n (gpointer mem,
429 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
431 if (G_UNLIKELY (!g_mem_initialized))
432 g_mem_init_nomessage();
434 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
435 G_STRLOC, n_blocks, n_block_bytes);
438 return g_realloc (mem, n_blocks * n_block_bytes);
443 * @n_blocks: the number of blocks to allocate
444 * @n_block_bytes: the size of each block in bytes
446 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
447 * but care is taken to detect possible overflow during multiplication.
450 * Returns: the allocated memory, or %NULL.
453 g_try_malloc_n (gsize n_blocks,
456 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
459 return g_try_malloc (n_blocks * n_block_bytes);
464 * @n_blocks: the number of blocks to allocate
465 * @n_block_bytes: the size of each block in bytes
467 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
468 * but care is taken to detect possible overflow during multiplication.
471 * Returns: the allocated memory, or %NULL
474 g_try_malloc0_n (gsize n_blocks,
477 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
480 return g_try_malloc0 (n_blocks * n_block_bytes);
485 * @mem: previously-allocated memory, or %NULL.
486 * @n_blocks: the number of blocks to allocate
487 * @n_block_bytes: the size of each block in bytes
489 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
490 * but care is taken to detect possible overflow during multiplication.
493 * Returns: the allocated memory, or %NULL.
496 g_try_realloc_n (gpointer mem,
500 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
503 return g_try_realloc (mem, n_blocks * n_block_bytes);
509 fallback_calloc (gsize n_blocks,
512 gsize l = n_blocks * n_block_bytes;
513 gpointer mem = glib_mem_vtable.malloc (l);
521 static gboolean vtable_set = FALSE;
524 * g_mem_is_system_malloc
526 * Checks whether the allocator used by g_malloc() is the system's
527 * malloc implementation. If it returns %TRUE memory allocated with
528 * malloc() can be used interchangeable with memory allocated using g_malloc().
529 * This function is useful for avoiding an extra copy of allocated memory returned
530 * by a non-GLib-based API.
532 * A different allocator can be set using g_mem_set_vtable().
534 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
537 g_mem_is_system_malloc (void)
544 * @vtable: table of memory allocation routines.
546 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
547 * custom memory allocation routines. <emphasis>This function must be called
548 * before using any other GLib functions.</emphasis> The @vtable only needs to
549 * provide malloc(), realloc(), and free() functions; GLib can provide default
550 * implementations of the others. The malloc() and realloc() implementations
551 * should return %NULL on failure, GLib will handle error-checking for you.
552 * @vtable is copied, so need not persist after this function has been called.
555 g_mem_set_vtable (GMemVTable *vtable)
559 if (vtable->malloc && vtable->realloc && vtable->free)
561 glib_mem_vtable.malloc = vtable->malloc;
562 glib_mem_vtable.realloc = vtable->realloc;
563 glib_mem_vtable.free = vtable->free;
564 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
565 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
566 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
570 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
573 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
577 /* --- memory profiling and checking --- */
578 #ifdef G_DISABLE_CHECKS
580 * glib_mem_profiler_table:
582 * A #GMemVTable containing profiling variants of the memory
583 * allocation functions. Use them together with g_mem_profile()
584 * in order to get information about the memory allocation pattern
587 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
592 #else /* !G_DISABLE_CHECKS */
599 static guint *profile_data = NULL;
600 static gsize profile_allocs = 0;
601 static gsize profile_zinit = 0;
602 static gsize profile_frees = 0;
603 static GMutex *gmem_profile_mutex = NULL;
604 #ifdef G_ENABLE_DEBUG
605 static volatile gsize g_trap_free_size = 0;
606 static volatile gsize g_trap_realloc_size = 0;
607 static volatile gsize g_trap_malloc_size = 0;
608 #endif /* G_ENABLE_DEBUG */
610 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
613 profiler_log (ProfilerJob job,
617 g_mutex_lock (gmem_profile_mutex);
620 profile_data = standard_calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
621 sizeof (profile_data[0]));
622 if (!profile_data) /* memory system kiddin' me, eh? */
624 g_mutex_unlock (gmem_profile_mutex);
629 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
630 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
631 (job & PROFILER_RELOC) != 0,
634 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
635 (job & PROFILER_RELOC) != 0,
639 if (job & PROFILER_ALLOC)
641 profile_allocs += n_bytes;
642 if (job & PROFILER_ZINIT)
643 profile_zinit += n_bytes;
646 profile_frees += n_bytes;
648 g_mutex_unlock (gmem_profile_mutex);
652 profile_print_locked (guint *local_data,
655 gboolean need_header = TRUE;
658 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
660 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
661 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
662 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
663 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
665 if (!t_malloc && !t_realloc && !t_free && !t_refree)
667 else if (need_header)
670 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
671 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
672 g_print (" | malloc() | free() | realloc() | realloc() | \n");
673 g_print ("===========|============|============|============|============|===========\n");
675 if (i < MEM_PROFILE_TABLE_SIZE)
676 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
677 i, t_malloc, t_free, t_realloc, t_refree,
678 (t_malloc - t_free + t_realloc - t_refree) * i);
679 else if (i >= MEM_PROFILE_TABLE_SIZE)
680 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
681 i, t_malloc, t_free, t_realloc, t_refree);
684 g_print (" --- none ---\n");
691 * Outputs a summary of memory usage.
693 * It outputs the frequency of allocations of different sizes,
694 * the total number of bytes which have been allocated,
695 * the total number of bytes which have been freed,
696 * and the difference between the previous two values, i.e. the number of bytes
699 * Note that this function will not output anything unless you have
700 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
706 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
711 if (G_UNLIKELY (!g_mem_initialized))
712 g_mem_init_nomessage();
714 g_mutex_lock (gmem_profile_mutex);
716 local_allocs = profile_allocs;
717 local_zinit = profile_zinit;
718 local_frees = profile_frees;
722 g_mutex_unlock (gmem_profile_mutex);
726 memcpy (local_data, profile_data,
727 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
729 g_mutex_unlock (gmem_profile_mutex);
731 g_print ("GLib Memory statistics (successful operations):\n");
732 profile_print_locked (local_data, TRUE);
733 g_print ("GLib Memory statistics (failing operations):\n");
734 profile_print_locked (local_data, FALSE);
735 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
736 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
737 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
738 "remaining=%"G_GSIZE_FORMAT"\n",
741 ((gdouble) local_zinit) / local_allocs * 100.0,
743 ((gdouble) local_frees) / local_allocs * 100.0,
744 local_allocs - local_frees);
748 profiler_try_malloc (gsize n_bytes)
752 #ifdef G_ENABLE_DEBUG
753 if (g_trap_malloc_size == n_bytes)
755 #endif /* G_ENABLE_DEBUG */
757 p = standard_malloc (sizeof (gsize) * 2 + n_bytes);
761 p[0] = 0; /* free count */
762 p[1] = n_bytes; /* length */
763 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
767 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
773 profiler_malloc (gsize n_bytes)
775 gpointer mem = profiler_try_malloc (n_bytes);
784 profiler_calloc (gsize n_blocks,
787 gsize l = n_blocks * n_block_bytes;
790 #ifdef G_ENABLE_DEBUG
791 if (g_trap_malloc_size == l)
793 #endif /* G_ENABLE_DEBUG */
795 p = standard_calloc (1, sizeof (gsize) * 2 + l);
799 p[0] = 0; /* free count */
800 p[1] = l; /* length */
801 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
806 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
814 profiler_free (gpointer mem)
819 if (p[0]) /* free count */
821 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
823 profiler_log (PROFILER_FREE,
829 #ifdef G_ENABLE_DEBUG
830 if (g_trap_free_size == p[1])
832 #endif /* G_ENABLE_DEBUG */
834 profiler_log (PROFILER_FREE,
837 memset (p + 2, 0xaa, p[1]);
839 /* for all those that miss standard_free (p); in this place, yes,
840 * we do leak all memory when profiling, and that is intentional
841 * to catch double frees. patch submissions are futile.
848 profiler_try_realloc (gpointer mem,
855 #ifdef G_ENABLE_DEBUG
856 if (g_trap_realloc_size == n_bytes)
858 #endif /* G_ENABLE_DEBUG */
860 if (mem && p[0]) /* free count */
862 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
863 "memory has been freed %"G_GSIZE_FORMAT" times already",
864 p + 2, (gsize) n_bytes, p[0]);
865 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
871 p = standard_realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
876 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
879 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
883 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
890 profiler_realloc (gpointer mem,
893 mem = profiler_try_realloc (mem, n_bytes);
901 static GMemVTable profiler_table = {
907 profiler_try_realloc,
909 GMemVTable *glib_mem_profiler_table = &profiler_table;
911 #endif /* !G_DISABLE_CHECKS */
913 #ifdef ENABLE_GC_FRIENDLY_DEFAULT
914 gboolean g_mem_gc_friendly = TRUE;
919 * This variable is %TRUE if the <envar>G_DEBUG</envar> environment variable
920 * includes the key <link linkend="G_DEBUG">gc-friendly</link>.
922 gboolean g_mem_gc_friendly = FALSE;
926 g_mem_init_nomessage (void)
930 const GDebugKey keys[] = {
931 { "gc-friendly", 1 },
934 if (g_mem_initialized)
936 /* don't use g_malloc/g_message here */
937 val = _g_getenv_nomalloc ("G_DEBUG", buffer);
938 flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
939 if (flags & 1) /* gc-friendly */
941 g_mem_gc_friendly = TRUE;
943 g_mem_initialized = TRUE;
947 _g_mem_thread_init_noprivate_nomessage (void)
949 /* we may only create mutexes here, locking/
950 * unlocking a mutex does not yet work.
952 g_mem_init_nomessage();
953 #ifndef G_DISABLE_CHECKS
954 gmem_profile_mutex = g_mutex_new ();