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"
45 #define MEM_PROFILE_TABLE_SIZE 4096
49 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
51 * If g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
54 /* --- variables --- */
55 static GMemVTable glib_mem_vtable = {
66 * @Short_Description: general memory-handling
67 * @Title: Memory Allocation
69 * These functions provide support for allocating and freeing memory.
72 * If any call to allocate memory fails, the application is terminated.
73 * This also means that there is no need to check if the call succeeded.
77 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
78 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
79 * bad things can happen, since these allocators may use different memory
80 * pools (and new/delete call constructors and destructors). See also
85 /* --- functions --- */
88 * @n_bytes: the number of bytes to allocate
90 * Allocates @n_bytes bytes of memory.
91 * If @n_bytes is 0 it returns %NULL.
93 * Returns: a pointer to the allocated memory
96 g_malloc (gsize n_bytes)
98 if (G_LIKELY (n_bytes))
102 mem = glib_mem_vtable.malloc (n_bytes);
103 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
107 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
111 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
118 * @n_bytes: the number of bytes to allocate
120 * Allocates @n_bytes bytes of memory, initialized to 0's.
121 * If @n_bytes is 0 it returns %NULL.
123 * Returns: a pointer to the allocated memory
126 g_malloc0 (gsize n_bytes)
128 if (G_LIKELY (n_bytes))
132 mem = glib_mem_vtable.calloc (1, n_bytes);
133 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
137 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
141 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
148 * @mem: (allow-none): the memory to reallocate
149 * @n_bytes: new size of the memory in bytes
151 * Reallocates the memory pointed to by @mem, so that it now has space for
152 * @n_bytes bytes of memory. It returns the new address of the memory, which may
153 * have been moved. @mem may be %NULL, in which case it's considered to
154 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
155 * and @mem will be freed unless it is %NULL.
157 * Returns: the new address of the allocated memory
160 g_realloc (gpointer mem,
165 if (G_LIKELY (n_bytes))
167 newmem = glib_mem_vtable.realloc (mem, n_bytes);
168 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
172 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
177 glib_mem_vtable.free (mem);
179 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
186 * @mem: (allow-none): the memory to free
188 * Frees the memory pointed to by @mem.
189 * If @mem is %NULL it simply returns.
192 g_free (gpointer mem)
195 glib_mem_vtable.free (mem);
196 TRACE(GLIB_MEM_FREE((void*) mem));
200 * g_clear_pointer: (skip)
201 * @pp: a pointer to a variable, struct member etc. holding a pointer
202 * @destroy: a function to which a gpointer can be passed, to destroy *@pp
204 * Clears a reference to a variable.
206 * @pp must not be %NULL.
208 * If the reference is %NULL then this function does nothing.
209 * Otherwise, the variable is destroyed using @destroy and the
210 * pointer is set to %NULL.
212 * This function is threadsafe and modifies the pointer atomically,
213 * using memory barriers where needed.
215 * A macro is also included that allows this function to be used without
220 #undef g_clear_pointer
222 g_clear_pointer (gpointer *pp,
223 GDestroyNotify destroy)
227 /* This is a little frustrating.
228 * Would be nice to have an atomic exchange (with no compare).
231 _p = g_atomic_pointer_get (pp);
232 while G_UNLIKELY (!g_atomic_pointer_compare_and_exchange (pp, _p, NULL));
240 * @n_bytes: number of bytes to allocate.
242 * Attempts to allocate @n_bytes, and returns %NULL on failure.
243 * Contrast with g_malloc(), which aborts the program on failure.
245 * Returns: the allocated memory, or %NULL.
248 g_try_malloc (gsize n_bytes)
252 if (G_LIKELY (n_bytes))
253 mem = glib_mem_vtable.try_malloc (n_bytes);
257 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
264 * @n_bytes: number of bytes to allocate
266 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
267 * failure. Contrast with g_malloc0(), which aborts the program on failure.
270 * Returns: the allocated memory, or %NULL
273 g_try_malloc0 (gsize n_bytes)
277 if (G_LIKELY (n_bytes))
278 mem = glib_mem_vtable.try_malloc (n_bytes);
283 memset (mem, 0, n_bytes);
290 * @mem: (allow-none): previously-allocated memory, or %NULL.
291 * @n_bytes: number of bytes to allocate.
293 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
294 * on failure. Contrast with g_realloc(), which aborts the program
295 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
297 * Returns: the allocated memory, or %NULL.
300 g_try_realloc (gpointer mem,
305 if (G_LIKELY (n_bytes))
306 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
311 glib_mem_vtable.free (mem);
314 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
320 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
324 * @n_blocks: the number of blocks to allocate
325 * @n_block_bytes: the size of each block in bytes
327 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
328 * but care is taken to detect possible overflow during multiplication.
331 * Returns: a pointer to the allocated memory
334 g_malloc_n (gsize n_blocks,
337 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
339 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
340 G_STRLOC, n_blocks, n_block_bytes);
343 return g_malloc (n_blocks * n_block_bytes);
348 * @n_blocks: the number of blocks to allocate
349 * @n_block_bytes: the size of each block in bytes
351 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
352 * but care is taken to detect possible overflow during multiplication.
355 * Returns: a pointer to the allocated memory
358 g_malloc0_n (gsize n_blocks,
361 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
363 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
364 G_STRLOC, n_blocks, n_block_bytes);
367 return g_malloc0 (n_blocks * n_block_bytes);
372 * @mem: (allow-none): the memory to reallocate
373 * @n_blocks: the number of blocks to allocate
374 * @n_block_bytes: the size of each block in bytes
376 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
377 * but care is taken to detect possible overflow during multiplication.
380 * Returns: the new address of the allocated memory
383 g_realloc_n (gpointer mem,
387 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
389 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
390 G_STRLOC, n_blocks, n_block_bytes);
393 return g_realloc (mem, n_blocks * n_block_bytes);
398 * @n_blocks: the number of blocks to allocate
399 * @n_block_bytes: the size of each block in bytes
401 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
402 * but care is taken to detect possible overflow during multiplication.
405 * Returns: the allocated memory, or %NULL.
408 g_try_malloc_n (gsize n_blocks,
411 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
414 return g_try_malloc (n_blocks * n_block_bytes);
419 * @n_blocks: the number of blocks to allocate
420 * @n_block_bytes: the size of each block in bytes
422 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
423 * but care is taken to detect possible overflow during multiplication.
426 * Returns: the allocated memory, or %NULL
429 g_try_malloc0_n (gsize n_blocks,
432 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
435 return g_try_malloc0 (n_blocks * n_block_bytes);
440 * @mem: (allow-none): previously-allocated memory, or %NULL.
441 * @n_blocks: the number of blocks to allocate
442 * @n_block_bytes: the size of each block in bytes
444 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
445 * but care is taken to detect possible overflow during multiplication.
448 * Returns: the allocated memory, or %NULL.
451 g_try_realloc_n (gpointer mem,
455 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
458 return g_try_realloc (mem, n_blocks * n_block_bytes);
464 fallback_calloc (gsize n_blocks,
467 gsize l = n_blocks * n_block_bytes;
468 gpointer mem = glib_mem_vtable.malloc (l);
476 static gboolean vtable_set = FALSE;
479 * g_mem_is_system_malloc:
481 * Checks whether the allocator used by g_malloc() is the system's
482 * malloc implementation. If it returns %TRUE memory allocated with
483 * malloc() can be used interchangeable with memory allocated using g_malloc().
484 * This function is useful for avoiding an extra copy of allocated memory returned
485 * by a non-GLib-based API.
487 * A different allocator can be set using g_mem_set_vtable().
489 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
492 g_mem_is_system_malloc (void)
499 * @vtable: table of memory allocation routines.
501 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
502 * custom memory allocation routines. <emphasis>This function must be called
503 * before using any other GLib functions.</emphasis> The @vtable only needs to
504 * provide malloc(), realloc(), and free() functions; GLib can provide default
505 * implementations of the others. The malloc() and realloc() implementations
506 * should return %NULL on failure, GLib will handle error-checking for you.
507 * @vtable is copied, so need not persist after this function has been called.
510 g_mem_set_vtable (GMemVTable *vtable)
514 if (vtable->malloc && vtable->realloc && vtable->free)
516 glib_mem_vtable.malloc = vtable->malloc;
517 glib_mem_vtable.realloc = vtable->realloc;
518 glib_mem_vtable.free = vtable->free;
519 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
520 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
521 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
525 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
528 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
532 /* --- memory profiling and checking --- */
533 #ifdef G_DISABLE_CHECKS
535 * glib_mem_profiler_table:
537 * A #GMemVTable containing profiling variants of the memory
538 * allocation functions. Use them together with g_mem_profile()
539 * in order to get information about the memory allocation pattern
542 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
547 #else /* !G_DISABLE_CHECKS */
554 static guint *profile_data = NULL;
555 static gsize profile_allocs = 0;
556 static gsize profile_zinit = 0;
557 static gsize profile_frees = 0;
558 static GMutex gmem_profile_mutex;
560 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
563 profiler_log (ProfilerJob job,
567 g_mutex_lock (&gmem_profile_mutex);
570 profile_data = calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
571 sizeof (profile_data[0]));
572 if (!profile_data) /* memory system kiddin' me, eh? */
574 g_mutex_unlock (&gmem_profile_mutex);
579 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
580 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
581 (job & PROFILER_RELOC) != 0,
584 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
585 (job & PROFILER_RELOC) != 0,
589 if (job & PROFILER_ALLOC)
591 profile_allocs += n_bytes;
592 if (job & PROFILER_ZINIT)
593 profile_zinit += n_bytes;
596 profile_frees += n_bytes;
598 g_mutex_unlock (&gmem_profile_mutex);
602 profile_print_locked (guint *local_data,
605 gboolean need_header = TRUE;
608 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
610 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
611 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
612 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
613 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
615 if (!t_malloc && !t_realloc && !t_free && !t_refree)
617 else if (need_header)
620 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
621 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
622 g_print (" | malloc() | free() | realloc() | realloc() | \n");
623 g_print ("===========|============|============|============|============|===========\n");
625 if (i < MEM_PROFILE_TABLE_SIZE)
626 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
627 i, t_malloc, t_free, t_realloc, t_refree,
628 (t_malloc - t_free + t_realloc - t_refree) * i);
629 else if (i >= MEM_PROFILE_TABLE_SIZE)
630 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
631 i, t_malloc, t_free, t_realloc, t_refree);
634 g_print (" --- none ---\n");
640 * Outputs a summary of memory usage.
642 * It outputs the frequency of allocations of different sizes,
643 * the total number of bytes which have been allocated,
644 * the total number of bytes which have been freed,
645 * and the difference between the previous two values, i.e. the number of bytes
648 * Note that this function will not output anything unless you have
649 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
655 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8];
660 g_mutex_lock (&gmem_profile_mutex);
662 local_allocs = profile_allocs;
663 local_zinit = profile_zinit;
664 local_frees = profile_frees;
668 g_mutex_unlock (&gmem_profile_mutex);
672 memcpy (local_data, profile_data,
673 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
675 g_mutex_unlock (&gmem_profile_mutex);
677 g_print ("GLib Memory statistics (successful operations):\n");
678 profile_print_locked (local_data, TRUE);
679 g_print ("GLib Memory statistics (failing operations):\n");
680 profile_print_locked (local_data, FALSE);
681 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
682 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
683 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
684 "remaining=%"G_GSIZE_FORMAT"\n",
687 ((gdouble) local_zinit) / local_allocs * 100.0,
689 ((gdouble) local_frees) / local_allocs * 100.0,
690 local_allocs - local_frees);
694 profiler_try_malloc (gsize n_bytes)
698 p = malloc (sizeof (gsize) * 2 + n_bytes);
702 p[0] = 0; /* free count */
703 p[1] = n_bytes; /* length */
704 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
708 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
714 profiler_malloc (gsize n_bytes)
716 gpointer mem = profiler_try_malloc (n_bytes);
725 profiler_calloc (gsize n_blocks,
728 gsize l = n_blocks * n_block_bytes;
731 p = calloc (1, sizeof (gsize) * 2 + l);
735 p[0] = 0; /* free count */
736 p[1] = l; /* length */
737 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
742 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
750 profiler_free (gpointer mem)
755 if (p[0]) /* free count */
757 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
759 profiler_log (PROFILER_FREE,
765 profiler_log (PROFILER_FREE,
768 memset (p + 2, 0xaa, p[1]);
770 /* for all those that miss free (p); in this place, yes,
771 * we do leak all memory when profiling, and that is intentional
772 * to catch double frees. patch submissions are futile.
779 profiler_try_realloc (gpointer mem,
786 if (mem && p[0]) /* free count */
788 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
789 "memory has been freed %"G_GSIZE_FORMAT" times already",
790 p + 2, (gsize) n_bytes, p[0]);
791 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
797 p = realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
802 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
805 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
809 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
816 profiler_realloc (gpointer mem,
819 mem = profiler_try_realloc (mem, n_bytes);
827 static GMemVTable profiler_table = {
833 profiler_try_realloc,
835 GMemVTable *glib_mem_profiler_table = &profiler_table;
837 #endif /* !G_DISABLE_CHECKS */