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"
47 #define MEM_PROFILE_TABLE_SIZE 4096
51 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
53 * If g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
56 /* --- variables --- */
57 static GMemVTable glib_mem_vtable = {
68 * @Short_Description: general memory-handling
69 * @Title: Memory Allocation
71 * These functions provide support for allocating and freeing memory.
74 * If any call to allocate memory fails, the application is terminated.
75 * This also means that there is no need to check if the call succeeded.
79 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
80 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
81 * bad things can happen, since these allocators may use different memory
82 * pools (and new/delete call constructors and destructors). See also
87 /* --- functions --- */
90 * @n_bytes: the number of bytes to allocate
92 * Allocates @n_bytes bytes of memory.
93 * If @n_bytes is 0 it returns %NULL.
95 * Returns: a pointer to the allocated memory
98 g_malloc (gsize n_bytes)
100 if (G_LIKELY (n_bytes))
104 mem = glib_mem_vtable.malloc (n_bytes);
105 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
109 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
113 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
120 * @n_bytes: the number of bytes to allocate
122 * Allocates @n_bytes bytes of memory, initialized to 0's.
123 * If @n_bytes is 0 it returns %NULL.
125 * Returns: a pointer to the allocated memory
128 g_malloc0 (gsize n_bytes)
130 if (G_LIKELY (n_bytes))
134 mem = glib_mem_vtable.calloc (1, n_bytes);
135 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
139 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
143 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
150 * @mem: the memory to reallocate
151 * @n_bytes: new size of the memory in bytes
153 * Reallocates the memory pointed to by @mem, so that it now has space for
154 * @n_bytes bytes of memory. It returns the new address of the memory, which may
155 * have been moved. @mem may be %NULL, in which case it's considered to
156 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
157 * and @mem will be freed unless it is %NULL.
159 * Returns: the new address of the allocated memory
162 g_realloc (gpointer mem,
167 if (G_LIKELY (n_bytes))
169 newmem = glib_mem_vtable.realloc (mem, n_bytes);
170 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
174 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
179 glib_mem_vtable.free (mem);
181 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
188 * @mem: the memory to free
190 * Frees the memory pointed to by @mem.
191 * If @mem is %NULL it simply returns.
194 g_free (gpointer mem)
197 glib_mem_vtable.free (mem);
198 TRACE(GLIB_MEM_FREE((void*) mem));
202 * g_clear_pointer: (skip)
203 * @pp: a pointer to a variable, struct member etc. holding a pointer
204 * @destroy: a function to which a gpointer can be passed, to destroy *@pp
206 * Clears a reference to a variable.
208 * @pp must not be %NULL.
210 * If the reference is %NULL then this function does nothing.
211 * Otherwise, the variable is destroyed using @destroy and the
212 * pointer is set to %NULL.
214 * This function is threadsafe and modifies the pointer atomically,
215 * using memory barriers where needed.
217 * A macro is also included that allows this function to be used without
222 #undef g_clear_pointer
224 g_clear_pointer (gpointer *pp,
225 GDestroyNotify destroy)
229 /* This is a little frustrating.
230 * Would be nice to have an atomic exchange (with no compare).
233 _p = g_atomic_pointer_get (pp);
234 while G_UNLIKELY (!g_atomic_pointer_compare_and_exchange (pp, _p, NULL));
242 * @n_bytes: number of bytes to allocate.
244 * Attempts to allocate @n_bytes, and returns %NULL on failure.
245 * Contrast with g_malloc(), which aborts the program on failure.
247 * Returns: the allocated memory, or %NULL.
250 g_try_malloc (gsize n_bytes)
254 if (G_LIKELY (n_bytes))
255 mem = glib_mem_vtable.try_malloc (n_bytes);
259 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
266 * @n_bytes: number of bytes to allocate
268 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
269 * failure. Contrast with g_malloc0(), which aborts the program on failure.
272 * Returns: the allocated memory, or %NULL
275 g_try_malloc0 (gsize n_bytes)
279 if (G_LIKELY (n_bytes))
280 mem = glib_mem_vtable.try_malloc (n_bytes);
285 memset (mem, 0, n_bytes);
292 * @mem: (allow-none): previously-allocated memory, or %NULL.
293 * @n_bytes: number of bytes to allocate.
295 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
296 * on failure. Contrast with g_realloc(), which aborts the program
297 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
299 * Returns: the allocated memory, or %NULL.
302 g_try_realloc (gpointer mem,
307 if (G_LIKELY (n_bytes))
308 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
313 glib_mem_vtable.free (mem);
316 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
322 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
326 * @n_blocks: the number of blocks to allocate
327 * @n_block_bytes: the size of each block in bytes
329 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
330 * but care is taken to detect possible overflow during multiplication.
333 * Returns: a pointer to the allocated memory
336 g_malloc_n (gsize n_blocks,
339 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
341 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
342 G_STRLOC, n_blocks, n_block_bytes);
345 return g_malloc (n_blocks * n_block_bytes);
350 * @n_blocks: the number of blocks to allocate
351 * @n_block_bytes: the size of each block in bytes
353 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
354 * but care is taken to detect possible overflow during multiplication.
357 * Returns: a pointer to the allocated memory
360 g_malloc0_n (gsize n_blocks,
363 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
365 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
366 G_STRLOC, n_blocks, n_block_bytes);
369 return g_malloc0 (n_blocks * n_block_bytes);
374 * @mem: the memory to reallocate
375 * @n_blocks: the number of blocks to allocate
376 * @n_block_bytes: the size of each block in bytes
378 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
379 * but care is taken to detect possible overflow during multiplication.
382 * Returns: the new address of the allocated memory
385 g_realloc_n (gpointer mem,
389 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
391 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
392 G_STRLOC, n_blocks, n_block_bytes);
395 return g_realloc (mem, n_blocks * n_block_bytes);
400 * @n_blocks: the number of blocks to allocate
401 * @n_block_bytes: the size of each block in bytes
403 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
404 * but care is taken to detect possible overflow during multiplication.
407 * Returns: the allocated memory, or %NULL.
410 g_try_malloc_n (gsize n_blocks,
413 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
416 return g_try_malloc (n_blocks * n_block_bytes);
421 * @n_blocks: the number of blocks to allocate
422 * @n_block_bytes: the size of each block in bytes
424 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
425 * but care is taken to detect possible overflow during multiplication.
428 * Returns: the allocated memory, or %NULL
431 g_try_malloc0_n (gsize n_blocks,
434 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
437 return g_try_malloc0 (n_blocks * n_block_bytes);
442 * @mem: (allow-none): previously-allocated memory, or %NULL.
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_realloc(), 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_realloc_n (gpointer mem,
457 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
460 return g_try_realloc (mem, n_blocks * n_block_bytes);
466 fallback_calloc (gsize n_blocks,
469 gsize l = n_blocks * n_block_bytes;
470 gpointer mem = glib_mem_vtable.malloc (l);
478 static gboolean vtable_set = FALSE;
481 * g_mem_is_system_malloc:
483 * Checks whether the allocator used by g_malloc() is the system's
484 * malloc implementation. If it returns %TRUE memory allocated with
485 * malloc() can be used interchangeable with memory allocated using g_malloc().
486 * This function is useful for avoiding an extra copy of allocated memory returned
487 * by a non-GLib-based API.
489 * A different allocator can be set using g_mem_set_vtable().
491 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
494 g_mem_is_system_malloc (void)
501 * @vtable: table of memory allocation routines.
503 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
504 * custom memory allocation routines. <emphasis>This function must be called
505 * before using any other GLib functions.</emphasis> The @vtable only needs to
506 * provide malloc(), realloc(), and free() functions; GLib can provide default
507 * implementations of the others. The malloc() and realloc() implementations
508 * should return %NULL on failure, GLib will handle error-checking for you.
509 * @vtable is copied, so need not persist after this function has been called.
512 g_mem_set_vtable (GMemVTable *vtable)
516 if (vtable->malloc && vtable->realloc && vtable->free)
518 glib_mem_vtable.malloc = vtable->malloc;
519 glib_mem_vtable.realloc = vtable->realloc;
520 glib_mem_vtable.free = vtable->free;
521 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
522 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
523 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
527 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
530 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
534 /* --- memory profiling and checking --- */
535 #ifdef G_DISABLE_CHECKS
537 * glib_mem_profiler_table:
539 * A #GMemVTable containing profiling variants of the memory
540 * allocation functions. Use them together with g_mem_profile()
541 * in order to get information about the memory allocation pattern
544 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
549 #else /* !G_DISABLE_CHECKS */
556 static guint *profile_data = NULL;
557 static gsize profile_allocs = 0;
558 static gsize profile_zinit = 0;
559 static gsize profile_frees = 0;
560 static GMutex gmem_profile_mutex;
561 #ifdef G_ENABLE_DEBUG
562 static volatile gsize g_trap_free_size = 0;
563 static volatile gsize g_trap_realloc_size = 0;
564 static volatile gsize g_trap_malloc_size = 0;
565 #endif /* G_ENABLE_DEBUG */
567 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
570 profiler_log (ProfilerJob job,
574 g_mutex_lock (&gmem_profile_mutex);
577 profile_data = calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
578 sizeof (profile_data[0]));
579 if (!profile_data) /* memory system kiddin' me, eh? */
581 g_mutex_unlock (&gmem_profile_mutex);
586 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
587 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
588 (job & PROFILER_RELOC) != 0,
591 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
592 (job & PROFILER_RELOC) != 0,
596 if (job & PROFILER_ALLOC)
598 profile_allocs += n_bytes;
599 if (job & PROFILER_ZINIT)
600 profile_zinit += n_bytes;
603 profile_frees += n_bytes;
605 g_mutex_unlock (&gmem_profile_mutex);
609 profile_print_locked (guint *local_data,
612 gboolean need_header = TRUE;
615 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
617 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
618 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
619 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
620 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
622 if (!t_malloc && !t_realloc && !t_free && !t_refree)
624 else if (need_header)
627 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
628 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
629 g_print (" | malloc() | free() | realloc() | realloc() | \n");
630 g_print ("===========|============|============|============|============|===========\n");
632 if (i < MEM_PROFILE_TABLE_SIZE)
633 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
634 i, t_malloc, t_free, t_realloc, t_refree,
635 (t_malloc - t_free + t_realloc - t_refree) * i);
636 else if (i >= MEM_PROFILE_TABLE_SIZE)
637 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
638 i, t_malloc, t_free, t_realloc, t_refree);
641 g_print (" --- none ---\n");
647 * Outputs a summary of memory usage.
649 * It outputs the frequency of allocations of different sizes,
650 * the total number of bytes which have been allocated,
651 * the total number of bytes which have been freed,
652 * and the difference between the previous two values, i.e. the number of bytes
655 * Note that this function will not output anything unless you have
656 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
662 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8];
667 g_mutex_lock (&gmem_profile_mutex);
669 local_allocs = profile_allocs;
670 local_zinit = profile_zinit;
671 local_frees = profile_frees;
675 g_mutex_unlock (&gmem_profile_mutex);
679 memcpy (local_data, profile_data,
680 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
682 g_mutex_unlock (&gmem_profile_mutex);
684 g_print ("GLib Memory statistics (successful operations):\n");
685 profile_print_locked (local_data, TRUE);
686 g_print ("GLib Memory statistics (failing operations):\n");
687 profile_print_locked (local_data, FALSE);
688 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
689 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
690 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
691 "remaining=%"G_GSIZE_FORMAT"\n",
694 ((gdouble) local_zinit) / local_allocs * 100.0,
696 ((gdouble) local_frees) / local_allocs * 100.0,
697 local_allocs - local_frees);
701 profiler_try_malloc (gsize n_bytes)
705 #ifdef G_ENABLE_DEBUG
706 if (g_trap_malloc_size == n_bytes)
708 #endif /* G_ENABLE_DEBUG */
710 p = malloc (sizeof (gsize) * 2 + n_bytes);
714 p[0] = 0; /* free count */
715 p[1] = n_bytes; /* length */
716 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
720 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
726 profiler_malloc (gsize n_bytes)
728 gpointer mem = profiler_try_malloc (n_bytes);
737 profiler_calloc (gsize n_blocks,
740 gsize l = n_blocks * n_block_bytes;
743 #ifdef G_ENABLE_DEBUG
744 if (g_trap_malloc_size == l)
746 #endif /* G_ENABLE_DEBUG */
748 p = calloc (1, sizeof (gsize) * 2 + l);
752 p[0] = 0; /* free count */
753 p[1] = l; /* length */
754 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
759 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
767 profiler_free (gpointer mem)
772 if (p[0]) /* free count */
774 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
776 profiler_log (PROFILER_FREE,
782 #ifdef G_ENABLE_DEBUG
783 if (g_trap_free_size == p[1])
785 #endif /* G_ENABLE_DEBUG */
787 profiler_log (PROFILER_FREE,
790 memset (p + 2, 0xaa, p[1]);
792 /* for all those that miss free (p); in this place, yes,
793 * we do leak all memory when profiling, and that is intentional
794 * to catch double frees. patch submissions are futile.
801 profiler_try_realloc (gpointer mem,
808 #ifdef G_ENABLE_DEBUG
809 if (g_trap_realloc_size == n_bytes)
811 #endif /* G_ENABLE_DEBUG */
813 if (mem && p[0]) /* free count */
815 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
816 "memory has been freed %"G_GSIZE_FORMAT" times already",
817 p + 2, (gsize) n_bytes, p[0]);
818 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
824 p = realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
829 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
832 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
836 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
843 profiler_realloc (gpointer mem,
846 mem = profiler_try_realloc (mem, n_bytes);
854 static GMemVTable profiler_table = {
860 profiler_try_realloc,
862 GMemVTable *glib_mem_profiler_table = &profiler_table;
864 #endif /* !G_DISABLE_CHECKS */