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, see <http://www.gnu.org/licenses/>.
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
38 #include "gbacktrace.h"
39 #include "gtestutils.h"
41 #include "glib_trace.h"
43 #define MEM_PROFILE_TABLE_SIZE 4096
47 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
49 * If g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
52 /* --- variables --- */
53 static GMemVTable glib_mem_vtable = {
64 * @Short_Description: general memory-handling
65 * @Title: Memory Allocation
67 * These functions provide support for allocating and freeing memory.
70 * If any call to allocate memory fails, the application is terminated.
71 * This also means that there is no need to check if the call succeeded.
75 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
76 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
77 * bad things can happen, since these allocators may use different memory
78 * pools (and new/delete call constructors and destructors). See also
83 /* --- functions --- */
86 * @n_bytes: the number of bytes to allocate
88 * Allocates @n_bytes bytes of memory.
89 * If @n_bytes is 0 it returns %NULL.
91 * Returns: a pointer to the allocated memory
94 g_malloc (gsize n_bytes)
96 if (G_LIKELY (n_bytes))
100 mem = glib_mem_vtable.malloc (n_bytes);
101 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
105 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
109 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
116 * @n_bytes: the number of bytes to allocate
118 * Allocates @n_bytes bytes of memory, initialized to 0's.
119 * If @n_bytes is 0 it returns %NULL.
121 * Returns: a pointer to the allocated memory
124 g_malloc0 (gsize n_bytes)
126 if (G_LIKELY (n_bytes))
130 mem = glib_mem_vtable.calloc (1, n_bytes);
131 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
135 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
139 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
146 * @mem: (allow-none): the memory to reallocate
147 * @n_bytes: new size of the memory in bytes
149 * Reallocates the memory pointed to by @mem, so that it now has space for
150 * @n_bytes bytes of memory. It returns the new address of the memory, which may
151 * have been moved. @mem may be %NULL, in which case it's considered to
152 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
153 * and @mem will be freed unless it is %NULL.
155 * Returns: the new address of the allocated memory
158 g_realloc (gpointer mem,
163 if (G_LIKELY (n_bytes))
165 newmem = glib_mem_vtable.realloc (mem, n_bytes);
166 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
170 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
175 glib_mem_vtable.free (mem);
177 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
184 * @mem: (allow-none): the memory to free
186 * Frees the memory pointed to by @mem.
187 * If @mem is %NULL it simply returns.
190 g_free (gpointer mem)
193 glib_mem_vtable.free (mem);
194 TRACE(GLIB_MEM_FREE((void*) mem));
198 * g_clear_pointer: (skip)
199 * @pp: a pointer to a variable, struct member etc. holding a pointer
200 * @destroy: a function to which a gpointer can be passed, to destroy *@pp
202 * Clears a reference to a variable.
204 * @pp must not be %NULL.
206 * If the reference is %NULL then this function does nothing.
207 * Otherwise, the variable is destroyed using @destroy and the
208 * pointer is set to %NULL.
210 * This function is threadsafe and modifies the pointer atomically,
211 * using memory barriers where needed.
213 * A macro is also included that allows this function to be used without
218 #undef g_clear_pointer
220 g_clear_pointer (gpointer *pp,
221 GDestroyNotify destroy)
225 /* This is a little frustrating.
226 * Would be nice to have an atomic exchange (with no compare).
229 _p = g_atomic_pointer_get (pp);
230 while G_UNLIKELY (!g_atomic_pointer_compare_and_exchange (pp, _p, NULL));
238 * @n_bytes: number of bytes to allocate.
240 * Attempts to allocate @n_bytes, and returns %NULL on failure.
241 * Contrast with g_malloc(), which aborts the program on failure.
243 * Returns: the allocated memory, or %NULL.
246 g_try_malloc (gsize n_bytes)
250 if (G_LIKELY (n_bytes))
251 mem = glib_mem_vtable.try_malloc (n_bytes);
255 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
262 * @n_bytes: number of bytes to allocate
264 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
265 * failure. Contrast with g_malloc0(), which aborts the program on failure.
268 * Returns: the allocated memory, or %NULL
271 g_try_malloc0 (gsize n_bytes)
275 if (G_LIKELY (n_bytes))
276 mem = glib_mem_vtable.try_malloc (n_bytes);
281 memset (mem, 0, n_bytes);
288 * @mem: (allow-none): previously-allocated memory, or %NULL.
289 * @n_bytes: number of bytes to allocate.
291 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
292 * on failure. Contrast with g_realloc(), which aborts the program
293 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
295 * Returns: the allocated memory, or %NULL.
298 g_try_realloc (gpointer mem,
303 if (G_LIKELY (n_bytes))
304 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
309 glib_mem_vtable.free (mem);
312 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
318 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
322 * @n_blocks: the number of blocks to allocate
323 * @n_block_bytes: the size of each block in bytes
325 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
326 * but care is taken to detect possible overflow during multiplication.
329 * Returns: a pointer to the allocated memory
332 g_malloc_n (gsize n_blocks,
335 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
337 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
338 G_STRLOC, n_blocks, n_block_bytes);
341 return g_malloc (n_blocks * n_block_bytes);
346 * @n_blocks: the number of blocks to allocate
347 * @n_block_bytes: the size of each block in bytes
349 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
350 * but care is taken to detect possible overflow during multiplication.
353 * Returns: a pointer to the allocated memory
356 g_malloc0_n (gsize n_blocks,
359 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
361 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
362 G_STRLOC, n_blocks, n_block_bytes);
365 return g_malloc0 (n_blocks * n_block_bytes);
370 * @mem: (allow-none): the memory to reallocate
371 * @n_blocks: the number of blocks to allocate
372 * @n_block_bytes: the size of each block in bytes
374 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
375 * but care is taken to detect possible overflow during multiplication.
378 * Returns: the new address of the allocated memory
381 g_realloc_n (gpointer mem,
385 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
387 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
388 G_STRLOC, n_blocks, n_block_bytes);
391 return g_realloc (mem, n_blocks * n_block_bytes);
396 * @n_blocks: the number of blocks to allocate
397 * @n_block_bytes: the size of each block in bytes
399 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
400 * but care is taken to detect possible overflow during multiplication.
403 * Returns: the allocated memory, or %NULL.
406 g_try_malloc_n (gsize n_blocks,
409 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
412 return g_try_malloc (n_blocks * n_block_bytes);
417 * @n_blocks: the number of blocks to allocate
418 * @n_block_bytes: the size of each block in bytes
420 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
421 * but care is taken to detect possible overflow during multiplication.
424 * Returns: the allocated memory, or %NULL
427 g_try_malloc0_n (gsize n_blocks,
430 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
433 return g_try_malloc0 (n_blocks * n_block_bytes);
438 * @mem: (allow-none): previously-allocated memory, or %NULL.
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_realloc(), 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_realloc_n (gpointer mem,
453 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
456 return g_try_realloc (mem, n_blocks * n_block_bytes);
462 fallback_calloc (gsize n_blocks,
465 gsize l = n_blocks * n_block_bytes;
466 gpointer mem = glib_mem_vtable.malloc (l);
474 static gboolean vtable_set = FALSE;
477 * g_mem_is_system_malloc:
479 * Checks whether the allocator used by g_malloc() is the system's
480 * malloc implementation. If it returns %TRUE memory allocated with
481 * malloc() can be used interchangeable with memory allocated using g_malloc().
482 * This function is useful for avoiding an extra copy of allocated memory returned
483 * by a non-GLib-based API.
485 * A different allocator can be set using g_mem_set_vtable().
487 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
490 g_mem_is_system_malloc (void)
497 * @vtable: table of memory allocation routines.
499 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
500 * custom memory allocation routines. <emphasis>This function must be called
501 * before using any other GLib functions.</emphasis> The @vtable only needs to
502 * provide malloc(), realloc(), and free() functions; GLib can provide default
503 * implementations of the others. The malloc() and realloc() implementations
504 * should return %NULL on failure, GLib will handle error-checking for you.
505 * @vtable is copied, so need not persist after this function has been called.
508 g_mem_set_vtable (GMemVTable *vtable)
512 if (vtable->malloc && vtable->realloc && vtable->free)
514 glib_mem_vtable.malloc = vtable->malloc;
515 glib_mem_vtable.realloc = vtable->realloc;
516 glib_mem_vtable.free = vtable->free;
517 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
518 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
519 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
523 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
526 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
530 /* --- memory profiling and checking --- */
531 #ifdef G_DISABLE_CHECKS
533 * glib_mem_profiler_table:
535 * A #GMemVTable containing profiling variants of the memory
536 * allocation functions. Use them together with g_mem_profile()
537 * in order to get information about the memory allocation pattern
540 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
545 #else /* !G_DISABLE_CHECKS */
552 static guint *profile_data = NULL;
553 static gsize profile_allocs = 0;
554 static gsize profile_zinit = 0;
555 static gsize profile_frees = 0;
556 static GMutex gmem_profile_mutex;
558 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
561 profiler_log (ProfilerJob job,
565 g_mutex_lock (&gmem_profile_mutex);
568 profile_data = calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
569 sizeof (profile_data[0]));
570 if (!profile_data) /* memory system kiddin' me, eh? */
572 g_mutex_unlock (&gmem_profile_mutex);
577 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
578 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
579 (job & PROFILER_RELOC) != 0,
582 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
583 (job & PROFILER_RELOC) != 0,
587 if (job & PROFILER_ALLOC)
589 profile_allocs += n_bytes;
590 if (job & PROFILER_ZINIT)
591 profile_zinit += n_bytes;
594 profile_frees += n_bytes;
596 g_mutex_unlock (&gmem_profile_mutex);
600 profile_print_locked (guint *local_data,
603 gboolean need_header = TRUE;
606 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
608 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
609 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
610 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
611 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
613 if (!t_malloc && !t_realloc && !t_free && !t_refree)
615 else if (need_header)
618 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
619 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
620 g_print (" | malloc() | free() | realloc() | realloc() | \n");
621 g_print ("===========|============|============|============|============|===========\n");
623 if (i < MEM_PROFILE_TABLE_SIZE)
624 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
625 i, t_malloc, t_free, t_realloc, t_refree,
626 (t_malloc - t_free + t_realloc - t_refree) * i);
627 else if (i >= MEM_PROFILE_TABLE_SIZE)
628 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
629 i, t_malloc, t_free, t_realloc, t_refree);
632 g_print (" --- none ---\n");
638 * Outputs a summary of memory usage.
640 * It outputs the frequency of allocations of different sizes,
641 * the total number of bytes which have been allocated,
642 * the total number of bytes which have been freed,
643 * and the difference between the previous two values, i.e. the number of bytes
646 * Note that this function will not output anything unless you have
647 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
653 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8];
658 g_mutex_lock (&gmem_profile_mutex);
660 local_allocs = profile_allocs;
661 local_zinit = profile_zinit;
662 local_frees = profile_frees;
666 g_mutex_unlock (&gmem_profile_mutex);
670 memcpy (local_data, profile_data,
671 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
673 g_mutex_unlock (&gmem_profile_mutex);
675 g_print ("GLib Memory statistics (successful operations):\n");
676 profile_print_locked (local_data, TRUE);
677 g_print ("GLib Memory statistics (failing operations):\n");
678 profile_print_locked (local_data, FALSE);
679 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
680 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
681 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
682 "remaining=%"G_GSIZE_FORMAT"\n",
685 ((gdouble) local_zinit) / local_allocs * 100.0,
687 ((gdouble) local_frees) / local_allocs * 100.0,
688 local_allocs - local_frees);
692 profiler_try_malloc (gsize n_bytes)
696 p = malloc (sizeof (gsize) * 2 + n_bytes);
700 p[0] = 0; /* free count */
701 p[1] = n_bytes; /* length */
702 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
706 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
712 profiler_malloc (gsize n_bytes)
714 gpointer mem = profiler_try_malloc (n_bytes);
723 profiler_calloc (gsize n_blocks,
726 gsize l = n_blocks * n_block_bytes;
729 p = calloc (1, sizeof (gsize) * 2 + l);
733 p[0] = 0; /* free count */
734 p[1] = l; /* length */
735 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
740 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
748 profiler_free (gpointer mem)
753 if (p[0]) /* free count */
755 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
757 profiler_log (PROFILER_FREE,
763 profiler_log (PROFILER_FREE,
766 memset (p + 2, 0xaa, p[1]);
768 /* for all those that miss free (p); in this place, yes,
769 * we do leak all memory when profiling, and that is intentional
770 * to catch double frees. patch submissions are futile.
777 profiler_try_realloc (gpointer mem,
784 if (mem && p[0]) /* free count */
786 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
787 "memory has been freed %"G_GSIZE_FORMAT" times already",
788 p + 2, (gsize) n_bytes, p[0]);
789 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
795 p = realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
800 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
803 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
807 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
814 profiler_realloc (gpointer mem,
817 mem = profiler_try_realloc (mem, n_bytes);
825 static GMemVTable profiler_table = {
831 profiler_try_realloc,
833 GMemVTable *glib_mem_profiler_table = &profiler_table;
835 #endif /* !G_DISABLE_CHECKS */