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.
185 * If @mem is %NULL it simply returns, so there is no need to check @mem
186 * against %NULL before calling this function.
189 g_free (gpointer mem)
192 glib_mem_vtable.free (mem);
193 TRACE(GLIB_MEM_FREE((void*) mem));
197 * g_clear_pointer: (skip)
198 * @pp: a pointer to a variable, struct member etc. holding a pointer
199 * @destroy: a function to which a gpointer can be passed, to destroy *@pp
201 * Clears a reference to a variable.
203 * @pp must not be %NULL.
205 * If the reference is %NULL then this function does nothing.
206 * Otherwise, the variable is destroyed using @destroy and the
207 * pointer is set to %NULL.
209 * A macro is also included that allows this function to be used without
214 #undef g_clear_pointer
216 g_clear_pointer (gpointer *pp,
217 GDestroyNotify destroy)
231 * @n_bytes: number of bytes to allocate.
233 * Attempts to allocate @n_bytes, and returns %NULL on failure.
234 * Contrast with g_malloc(), which aborts the program on failure.
236 * Returns: the allocated memory, or %NULL.
239 g_try_malloc (gsize n_bytes)
243 if (G_LIKELY (n_bytes))
244 mem = glib_mem_vtable.try_malloc (n_bytes);
248 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
255 * @n_bytes: number of bytes to allocate
257 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
258 * failure. Contrast with g_malloc0(), which aborts the program on failure.
261 * Returns: the allocated memory, or %NULL
264 g_try_malloc0 (gsize n_bytes)
268 if (G_LIKELY (n_bytes))
269 mem = glib_mem_vtable.try_malloc (n_bytes);
274 memset (mem, 0, n_bytes);
281 * @mem: (allow-none): previously-allocated memory, or %NULL.
282 * @n_bytes: number of bytes to allocate.
284 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
285 * on failure. Contrast with g_realloc(), which aborts the program
288 * If @mem is %NULL, behaves the same as g_try_malloc().
290 * Returns: the allocated memory, or %NULL.
293 g_try_realloc (gpointer mem,
298 if (G_LIKELY (n_bytes))
299 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
304 glib_mem_vtable.free (mem);
307 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
313 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
317 * @n_blocks: the number of blocks to allocate
318 * @n_block_bytes: the size of each block in bytes
320 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
321 * but care is taken to detect possible overflow during multiplication.
324 * Returns: a pointer to the allocated memory
327 g_malloc_n (gsize n_blocks,
330 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
332 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
333 G_STRLOC, n_blocks, n_block_bytes);
336 return g_malloc (n_blocks * n_block_bytes);
341 * @n_blocks: the number of blocks to allocate
342 * @n_block_bytes: the size of each block in bytes
344 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
345 * but care is taken to detect possible overflow during multiplication.
348 * Returns: a pointer to the allocated memory
351 g_malloc0_n (gsize n_blocks,
354 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
356 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
357 G_STRLOC, n_blocks, n_block_bytes);
360 return g_malloc0 (n_blocks * n_block_bytes);
365 * @mem: (allow-none): the memory to reallocate
366 * @n_blocks: the number of blocks to allocate
367 * @n_block_bytes: the size of each block in bytes
369 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
370 * but care is taken to detect possible overflow during multiplication.
373 * Returns: the new address of the allocated memory
376 g_realloc_n (gpointer mem,
380 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
382 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
383 G_STRLOC, n_blocks, n_block_bytes);
386 return g_realloc (mem, n_blocks * n_block_bytes);
391 * @n_blocks: the number of blocks to allocate
392 * @n_block_bytes: the size of each block in bytes
394 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
395 * but care is taken to detect possible overflow during multiplication.
398 * Returns: the allocated memory, or %NULL.
401 g_try_malloc_n (gsize n_blocks,
404 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
407 return g_try_malloc (n_blocks * n_block_bytes);
412 * @n_blocks: the number of blocks to allocate
413 * @n_block_bytes: the size of each block in bytes
415 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
416 * but care is taken to detect possible overflow during multiplication.
419 * Returns: the allocated memory, or %NULL
422 g_try_malloc0_n (gsize n_blocks,
425 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
428 return g_try_malloc0 (n_blocks * n_block_bytes);
433 * @mem: (allow-none): previously-allocated memory, or %NULL.
434 * @n_blocks: the number of blocks to allocate
435 * @n_block_bytes: the size of each block in bytes
437 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
438 * but care is taken to detect possible overflow during multiplication.
441 * Returns: the allocated memory, or %NULL.
444 g_try_realloc_n (gpointer mem,
448 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
451 return g_try_realloc (mem, n_blocks * n_block_bytes);
457 fallback_calloc (gsize n_blocks,
460 gsize l = n_blocks * n_block_bytes;
461 gpointer mem = glib_mem_vtable.malloc (l);
469 static gboolean vtable_set = FALSE;
472 * g_mem_is_system_malloc:
474 * Checks whether the allocator used by g_malloc() is the system's
475 * malloc implementation. If it returns %TRUE memory allocated with
476 * malloc() can be used interchangeable with memory allocated using g_malloc().
477 * This function is useful for avoiding an extra copy of allocated memory returned
478 * by a non-GLib-based API.
480 * A different allocator can be set using g_mem_set_vtable().
482 * Returns: if %TRUE, malloc() and g_malloc() can be mixed.
485 g_mem_is_system_malloc (void)
492 * @vtable: table of memory allocation routines.
494 * Sets the #GMemVTable to use for memory allocation. You can use this
495 * to provide custom memory allocation routines.
497 * The @vtable only needs to provide malloc(), realloc(), and free()
498 * functions; GLib can provide default implementations of the others.
499 * The malloc() and realloc() implementations should return %NULL on
500 * failure, GLib will handle error-checking for you. @vtable is copied,
501 * so need not persist after this function has been called.
503 * Note that this function must be called before using any other GLib
507 g_mem_set_vtable (GMemVTable *vtable)
511 if (vtable->malloc && vtable->realloc && vtable->free)
513 glib_mem_vtable.malloc = vtable->malloc;
514 glib_mem_vtable.realloc = vtable->realloc;
515 glib_mem_vtable.free = vtable->free;
516 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
517 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
518 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
522 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
525 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
529 /* --- memory profiling and checking --- */
530 #ifdef G_DISABLE_CHECKS
532 * glib_mem_profiler_table:
534 * A #GMemVTable containing profiling variants of the memory
535 * allocation functions. Use them together with g_mem_profile()
536 * in order to get information about the memory allocation pattern
539 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
544 #else /* !G_DISABLE_CHECKS */
551 static guint *profile_data = NULL;
552 static gsize profile_allocs = 0;
553 static gsize profile_zinit = 0;
554 static gsize profile_frees = 0;
555 static GMutex gmem_profile_mutex;
557 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
560 profiler_log (ProfilerJob job,
564 g_mutex_lock (&gmem_profile_mutex);
567 profile_data = calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
568 sizeof (profile_data[0]));
569 if (!profile_data) /* memory system kiddin' me, eh? */
571 g_mutex_unlock (&gmem_profile_mutex);
576 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
577 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
578 (job & PROFILER_RELOC) != 0,
581 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
582 (job & PROFILER_RELOC) != 0,
586 if (job & PROFILER_ALLOC)
588 profile_allocs += n_bytes;
589 if (job & PROFILER_ZINIT)
590 profile_zinit += n_bytes;
593 profile_frees += n_bytes;
595 g_mutex_unlock (&gmem_profile_mutex);
599 profile_print_locked (guint *local_data,
602 gboolean need_header = TRUE;
605 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
607 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
608 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
609 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
610 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
612 if (!t_malloc && !t_realloc && !t_free && !t_refree)
614 else if (need_header)
617 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
618 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
619 g_print (" | malloc() | free() | realloc() | realloc() | \n");
620 g_print ("===========|============|============|============|============|===========\n");
622 if (i < MEM_PROFILE_TABLE_SIZE)
623 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
624 i, t_malloc, t_free, t_realloc, t_refree,
625 (t_malloc - t_free + t_realloc - t_refree) * i);
626 else if (i >= MEM_PROFILE_TABLE_SIZE)
627 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
628 i, t_malloc, t_free, t_realloc, t_refree);
631 g_print (" --- none ---\n");
637 * Outputs a summary of memory usage.
639 * It outputs the frequency of allocations of different sizes,
640 * the total number of bytes which have been allocated,
641 * the total number of bytes which have been freed,
642 * and the difference between the previous two values, i.e. the number of bytes
645 * Note that this function will not output anything unless you have
646 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
652 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8];
657 g_mutex_lock (&gmem_profile_mutex);
659 local_allocs = profile_allocs;
660 local_zinit = profile_zinit;
661 local_frees = profile_frees;
665 g_mutex_unlock (&gmem_profile_mutex);
669 memcpy (local_data, profile_data,
670 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
672 g_mutex_unlock (&gmem_profile_mutex);
674 g_print ("GLib Memory statistics (successful operations):\n");
675 profile_print_locked (local_data, TRUE);
676 g_print ("GLib Memory statistics (failing operations):\n");
677 profile_print_locked (local_data, FALSE);
678 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
679 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
680 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
681 "remaining=%"G_GSIZE_FORMAT"\n",
684 ((gdouble) local_zinit) / local_allocs * 100.0,
686 ((gdouble) local_frees) / local_allocs * 100.0,
687 local_allocs - local_frees);
691 profiler_try_malloc (gsize n_bytes)
695 p = malloc (sizeof (gsize) * 2 + n_bytes);
699 p[0] = 0; /* free count */
700 p[1] = n_bytes; /* length */
701 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
705 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
711 profiler_malloc (gsize n_bytes)
713 gpointer mem = profiler_try_malloc (n_bytes);
722 profiler_calloc (gsize n_blocks,
725 gsize l = n_blocks * n_block_bytes;
728 p = calloc (1, sizeof (gsize) * 2 + l);
732 p[0] = 0; /* free count */
733 p[1] = l; /* length */
734 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
739 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
747 profiler_free (gpointer mem)
752 if (p[0]) /* free count */
754 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
756 profiler_log (PROFILER_FREE,
762 profiler_log (PROFILER_FREE,
765 memset (p + 2, 0xaa, p[1]);
767 /* for all those that miss free (p); in this place, yes,
768 * we do leak all memory when profiling, and that is intentional
769 * to catch double frees. patch submissions are futile.
776 profiler_try_realloc (gpointer mem,
783 if (mem && p[0]) /* free count */
785 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
786 "memory has been freed %"G_GSIZE_FORMAT" times already",
787 p + 2, (gsize) n_bytes, p[0]);
788 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
794 p = realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
799 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
802 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
806 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
813 profiler_realloc (gpointer mem,
816 mem = profiler_try_realloc (mem, n_bytes);
824 static GMemVTable profiler_table = {
830 profiler_try_realloc,
832 GMemVTable *glib_mem_profiler_table = &profiler_table;
834 #endif /* !G_DISABLE_CHECKS */