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.
69 * If any call to allocate memory fails, the application is terminated.
70 * This also means that there is no need to check if the call succeeded.
72 * It's important to match g_malloc() (and wrappers such as g_new()) with
73 * g_free(), g_slice_alloc() and wrappers such as g_slice_new()) with
74 * g_slice_free(), plain malloc() with free(), and (if you're using C++)
75 * new with delete and new[] with delete[]. Otherwise bad things can happen,
76 * since these allocators may use different memory pools (and new/delete call
77 * constructors and destructors). See also g_mem_set_vtable().
80 /* --- functions --- */
83 * @n_bytes: the number of bytes to allocate
85 * Allocates @n_bytes bytes of memory.
86 * If @n_bytes is 0 it returns %NULL.
88 * Returns: a pointer to the allocated memory
91 g_malloc (gsize n_bytes)
93 if (G_LIKELY (n_bytes))
97 mem = glib_mem_vtable.malloc (n_bytes);
98 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
102 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
106 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
113 * @n_bytes: the number of bytes to allocate
115 * Allocates @n_bytes bytes of memory, initialized to 0's.
116 * If @n_bytes is 0 it returns %NULL.
118 * Returns: a pointer to the allocated memory
121 g_malloc0 (gsize n_bytes)
123 if (G_LIKELY (n_bytes))
127 mem = glib_mem_vtable.calloc (1, n_bytes);
128 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
132 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
136 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
143 * @mem: (allow-none): the memory to reallocate
144 * @n_bytes: new size of the memory in bytes
146 * Reallocates the memory pointed to by @mem, so that it now has space for
147 * @n_bytes bytes of memory. It returns the new address of the memory, which may
148 * have been moved. @mem may be %NULL, in which case it's considered to
149 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
150 * and @mem will be freed unless it is %NULL.
152 * Returns: the new address of the allocated memory
155 g_realloc (gpointer mem,
160 if (G_LIKELY (n_bytes))
162 newmem = glib_mem_vtable.realloc (mem, n_bytes);
163 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
167 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
172 glib_mem_vtable.free (mem);
174 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
181 * @mem: (allow-none): the memory to free
183 * Frees the memory pointed to by @mem.
184 * If @mem is %NULL it simply returns.
187 g_free (gpointer mem)
190 glib_mem_vtable.free (mem);
191 TRACE(GLIB_MEM_FREE((void*) mem));
195 * g_clear_pointer: (skip)
196 * @pp: a pointer to a variable, struct member etc. holding a pointer
197 * @destroy: a function to which a gpointer can be passed, to destroy *@pp
199 * Clears a reference to a variable.
201 * @pp must not be %NULL.
203 * If the reference is %NULL then this function does nothing.
204 * Otherwise, the variable is destroyed using @destroy and the
205 * pointer is set to %NULL.
207 * This function is threadsafe and modifies the pointer atomically,
208 * using memory barriers where needed.
210 * A macro is also included that allows this function to be used without
215 #undef g_clear_pointer
217 g_clear_pointer (gpointer *pp,
218 GDestroyNotify destroy)
222 /* This is a little frustrating.
223 * Would be nice to have an atomic exchange (with no compare).
226 _p = g_atomic_pointer_get (pp);
227 while G_UNLIKELY (!g_atomic_pointer_compare_and_exchange (pp, _p, NULL));
235 * @n_bytes: number of bytes to allocate.
237 * Attempts to allocate @n_bytes, and returns %NULL on failure.
238 * Contrast with g_malloc(), which aborts the program on failure.
240 * Returns: the allocated memory, or %NULL.
243 g_try_malloc (gsize n_bytes)
247 if (G_LIKELY (n_bytes))
248 mem = glib_mem_vtable.try_malloc (n_bytes);
252 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
259 * @n_bytes: number of bytes to allocate
261 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
262 * failure. Contrast with g_malloc0(), which aborts the program on failure.
265 * Returns: the allocated memory, or %NULL
268 g_try_malloc0 (gsize n_bytes)
272 if (G_LIKELY (n_bytes))
273 mem = glib_mem_vtable.try_malloc (n_bytes);
278 memset (mem, 0, n_bytes);
285 * @mem: (allow-none): previously-allocated memory, or %NULL.
286 * @n_bytes: number of bytes to allocate.
288 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
289 * on failure. Contrast with g_realloc(), which aborts the program
290 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
292 * Returns: the allocated memory, or %NULL.
295 g_try_realloc (gpointer mem,
300 if (G_LIKELY (n_bytes))
301 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
306 glib_mem_vtable.free (mem);
309 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
315 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
319 * @n_blocks: the number of blocks to allocate
320 * @n_block_bytes: the size of each block in bytes
322 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
323 * but care is taken to detect possible overflow during multiplication.
326 * Returns: a pointer to the allocated memory
329 g_malloc_n (gsize n_blocks,
332 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
334 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
335 G_STRLOC, n_blocks, n_block_bytes);
338 return g_malloc (n_blocks * n_block_bytes);
343 * @n_blocks: the number of blocks to allocate
344 * @n_block_bytes: the size of each block in bytes
346 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
347 * but care is taken to detect possible overflow during multiplication.
350 * Returns: a pointer to the allocated memory
353 g_malloc0_n (gsize n_blocks,
356 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
358 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
359 G_STRLOC, n_blocks, n_block_bytes);
362 return g_malloc0 (n_blocks * n_block_bytes);
367 * @mem: (allow-none): the memory to reallocate
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_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
372 * but care is taken to detect possible overflow during multiplication.
375 * Returns: the new address of the allocated memory
378 g_realloc_n (gpointer mem,
382 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
384 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
385 G_STRLOC, n_blocks, n_block_bytes);
388 return g_realloc (mem, n_blocks * n_block_bytes);
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_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
397 * but care is taken to detect possible overflow during multiplication.
400 * Returns: the allocated memory, or %NULL.
403 g_try_malloc_n (gsize n_blocks,
406 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
409 return g_try_malloc (n_blocks * n_block_bytes);
414 * @n_blocks: the number of blocks to allocate
415 * @n_block_bytes: the size of each block in bytes
417 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
418 * but care is taken to detect possible overflow during multiplication.
421 * Returns: the allocated memory, or %NULL
424 g_try_malloc0_n (gsize n_blocks,
427 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
430 return g_try_malloc0 (n_blocks * n_block_bytes);
435 * @mem: (allow-none): previously-allocated memory, or %NULL.
436 * @n_blocks: the number of blocks to allocate
437 * @n_block_bytes: the size of each block in bytes
439 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
440 * but care is taken to detect possible overflow during multiplication.
443 * Returns: the allocated memory, or %NULL.
446 g_try_realloc_n (gpointer mem,
450 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
453 return g_try_realloc (mem, n_blocks * n_block_bytes);
459 fallback_calloc (gsize n_blocks,
462 gsize l = n_blocks * n_block_bytes;
463 gpointer mem = glib_mem_vtable.malloc (l);
471 static gboolean vtable_set = FALSE;
474 * g_mem_is_system_malloc:
476 * Checks whether the allocator used by g_malloc() is the system's
477 * malloc implementation. If it returns %TRUE memory allocated with
478 * malloc() can be used interchangeable with memory allocated using g_malloc().
479 * This function is useful for avoiding an extra copy of allocated memory returned
480 * by a non-GLib-based API.
482 * A different allocator can be set using g_mem_set_vtable().
484 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
487 g_mem_is_system_malloc (void)
494 * @vtable: table of memory allocation routines.
496 * Sets the #GMemVTable to use for memory allocation. You can use this
497 * to provide custom memory allocation routines.
499 * The @vtable only needs to provide malloc(), realloc(), and free()
500 * functions; GLib can provide default implementations of the others.
501 * The malloc() and realloc() implementations should return %NULL on
502 * failure, GLib will handle error-checking for you. @vtable is copied,
503 * so need not persist after this function has been called.
505 * Note that this function must be called before using any other GLib
509 g_mem_set_vtable (GMemVTable *vtable)
513 if (vtable->malloc && vtable->realloc && vtable->free)
515 glib_mem_vtable.malloc = vtable->malloc;
516 glib_mem_vtable.realloc = vtable->realloc;
517 glib_mem_vtable.free = vtable->free;
518 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
519 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
520 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
524 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
527 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
531 /* --- memory profiling and checking --- */
532 #ifdef G_DISABLE_CHECKS
534 * glib_mem_profiler_table:
536 * A #GMemVTable containing profiling variants of the memory
537 * allocation functions. Use them together with g_mem_profile()
538 * in order to get information about the memory allocation pattern
541 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
546 #else /* !G_DISABLE_CHECKS */
553 static guint *profile_data = NULL;
554 static gsize profile_allocs = 0;
555 static gsize profile_zinit = 0;
556 static gsize profile_frees = 0;
557 static GMutex gmem_profile_mutex;
559 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
562 profiler_log (ProfilerJob job,
566 g_mutex_lock (&gmem_profile_mutex);
569 profile_data = calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
570 sizeof (profile_data[0]));
571 if (!profile_data) /* memory system kiddin' me, eh? */
573 g_mutex_unlock (&gmem_profile_mutex);
578 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
579 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
580 (job & PROFILER_RELOC) != 0,
583 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
584 (job & PROFILER_RELOC) != 0,
588 if (job & PROFILER_ALLOC)
590 profile_allocs += n_bytes;
591 if (job & PROFILER_ZINIT)
592 profile_zinit += n_bytes;
595 profile_frees += n_bytes;
597 g_mutex_unlock (&gmem_profile_mutex);
601 profile_print_locked (guint *local_data,
604 gboolean need_header = TRUE;
607 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
609 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
610 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
611 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
612 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
614 if (!t_malloc && !t_realloc && !t_free && !t_refree)
616 else if (need_header)
619 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
620 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
621 g_print (" | malloc() | free() | realloc() | realloc() | \n");
622 g_print ("===========|============|============|============|============|===========\n");
624 if (i < MEM_PROFILE_TABLE_SIZE)
625 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
626 i, t_malloc, t_free, t_realloc, t_refree,
627 (t_malloc - t_free + t_realloc - t_refree) * i);
628 else if (i >= MEM_PROFILE_TABLE_SIZE)
629 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
630 i, t_malloc, t_free, t_realloc, t_refree);
633 g_print (" --- none ---\n");
639 * Outputs a summary of memory usage.
641 * It outputs the frequency of allocations of different sizes,
642 * the total number of bytes which have been allocated,
643 * the total number of bytes which have been freed,
644 * and the difference between the previous two values, i.e. the number of bytes
647 * Note that this function will not output anything unless you have
648 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
654 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8];
659 g_mutex_lock (&gmem_profile_mutex);
661 local_allocs = profile_allocs;
662 local_zinit = profile_zinit;
663 local_frees = profile_frees;
667 g_mutex_unlock (&gmem_profile_mutex);
671 memcpy (local_data, profile_data,
672 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
674 g_mutex_unlock (&gmem_profile_mutex);
676 g_print ("GLib Memory statistics (successful operations):\n");
677 profile_print_locked (local_data, TRUE);
678 g_print ("GLib Memory statistics (failing operations):\n");
679 profile_print_locked (local_data, FALSE);
680 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
681 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
682 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
683 "remaining=%"G_GSIZE_FORMAT"\n",
686 ((gdouble) local_zinit) / local_allocs * 100.0,
688 ((gdouble) local_frees) / local_allocs * 100.0,
689 local_allocs - local_frees);
693 profiler_try_malloc (gsize n_bytes)
697 p = malloc (sizeof (gsize) * 2 + n_bytes);
701 p[0] = 0; /* free count */
702 p[1] = n_bytes; /* length */
703 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
707 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
713 profiler_malloc (gsize n_bytes)
715 gpointer mem = profiler_try_malloc (n_bytes);
724 profiler_calloc (gsize n_blocks,
727 gsize l = n_blocks * n_block_bytes;
730 p = calloc (1, sizeof (gsize) * 2 + l);
734 p[0] = 0; /* free count */
735 p[1] = l; /* length */
736 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
741 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
749 profiler_free (gpointer mem)
754 if (p[0]) /* free count */
756 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
758 profiler_log (PROFILER_FREE,
764 profiler_log (PROFILER_FREE,
767 memset (p + 2, 0xaa, p[1]);
769 /* for all those that miss free (p); in this place, yes,
770 * we do leak all memory when profiling, and that is intentional
771 * to catch double frees. patch submissions are futile.
778 profiler_try_realloc (gpointer mem,
785 if (mem && p[0]) /* free count */
787 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
788 "memory has been freed %"G_GSIZE_FORMAT" times already",
789 p + 2, (gsize) n_bytes, p[0]);
790 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
796 p = realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
801 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
804 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
808 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
815 profiler_realloc (gpointer mem,
818 mem = profiler_try_realloc (mem, n_bytes);
826 static GMemVTable profiler_table = {
832 profiler_try_realloc,
834 GMemVTable *glib_mem_profiler_table = &profiler_table;
836 #endif /* !G_DISABLE_CHECKS */