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 * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
54 * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
55 * match the corresponding GLib prototypes, keep configure.ac and gmem.h in sync here.
56 * g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
59 /* --- malloc wrappers --- */
60 #ifndef REALLOC_0_WORKS
62 standard_realloc (gpointer mem,
66 return malloc (n_bytes);
68 return realloc (mem, n_bytes);
70 #endif /* !REALLOC_0_WORKS */
72 #ifdef SANE_MALLOC_PROTOS
73 # define standard_malloc malloc
74 # ifdef REALLOC_0_WORKS
75 # define standard_realloc realloc
76 # endif /* REALLOC_0_WORKS */
77 # define standard_free free
78 # define standard_calloc calloc
79 # define standard_try_malloc malloc
80 # define standard_try_realloc realloc
81 #else /* !SANE_MALLOC_PROTOS */
83 standard_malloc (gsize n_bytes)
85 return malloc (n_bytes);
87 # ifdef REALLOC_0_WORKS
89 standard_realloc (gpointer mem,
92 return realloc (mem, n_bytes);
94 # endif /* REALLOC_0_WORKS */
96 standard_free (gpointer mem)
101 standard_calloc (gsize n_blocks,
104 return calloc (n_blocks, n_bytes);
106 #define standard_try_malloc standard_malloc
107 #define standard_try_realloc standard_realloc
108 #endif /* !SANE_MALLOC_PROTOS */
111 /* --- variables --- */
112 static GMemVTable glib_mem_vtable = {
118 standard_try_realloc,
123 * @Short_Description: general memory-handling
124 * @Title: Memory Allocation
126 * These functions provide support for allocating and freeing memory.
129 * If any call to allocate memory fails, the application is terminated.
130 * This also means that there is no need to check if the call succeeded.
134 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
135 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
136 * bad things can happen, since these allocators may use different memory
137 * pools (and new/delete call constructors and destructors). See also
138 * g_mem_set_vtable().
142 /* --- functions --- */
145 * @n_bytes: the number of bytes to allocate
147 * Allocates @n_bytes bytes of memory.
148 * If @n_bytes is 0 it returns %NULL.
150 * Returns: a pointer to the allocated memory
153 g_malloc (gsize n_bytes)
155 if (G_LIKELY (n_bytes))
159 mem = glib_mem_vtable.malloc (n_bytes);
160 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
164 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
168 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
175 * @n_bytes: the number of bytes to allocate
177 * Allocates @n_bytes bytes of memory, initialized to 0's.
178 * If @n_bytes is 0 it returns %NULL.
180 * Returns: a pointer to the allocated memory
183 g_malloc0 (gsize n_bytes)
185 if (G_LIKELY (n_bytes))
189 mem = glib_mem_vtable.calloc (1, n_bytes);
190 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
194 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
198 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
205 * @mem: the memory to reallocate
206 * @n_bytes: new size of the memory in bytes
208 * Reallocates the memory pointed to by @mem, so that it now has space for
209 * @n_bytes bytes of memory. It returns the new address of the memory, which may
210 * have been moved. @mem may be %NULL, in which case it's considered to
211 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
212 * and @mem will be freed unless it is %NULL.
214 * Returns: the new address of the allocated memory
217 g_realloc (gpointer mem,
222 if (G_LIKELY (n_bytes))
224 newmem = glib_mem_vtable.realloc (mem, n_bytes);
225 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
229 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
234 glib_mem_vtable.free (mem);
236 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
243 * @mem: the memory to free
245 * Frees the memory pointed to by @mem.
246 * If @mem is %NULL it simply returns.
249 g_free (gpointer mem)
252 glib_mem_vtable.free (mem);
253 TRACE(GLIB_MEM_FREE((void*) mem));
258 * @n_bytes: number of bytes to allocate.
260 * Attempts to allocate @n_bytes, and returns %NULL on failure.
261 * Contrast with g_malloc(), which aborts the program on failure.
263 * Returns: the allocated memory, or %NULL.
266 g_try_malloc (gsize n_bytes)
270 if (G_LIKELY (n_bytes))
271 mem = glib_mem_vtable.try_malloc (n_bytes);
275 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
282 * @n_bytes: number of bytes to allocate
284 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
285 * failure. Contrast with g_malloc0(), which aborts the program on failure.
288 * Returns: the allocated memory, or %NULL
291 g_try_malloc0 (gsize n_bytes)
295 if (G_LIKELY (n_bytes))
296 mem = glib_mem_vtable.try_malloc (n_bytes);
301 memset (mem, 0, n_bytes);
308 * @mem: previously-allocated memory, or %NULL.
309 * @n_bytes: number of bytes to allocate.
311 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
312 * on failure. Contrast with g_realloc(), which aborts the program
313 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
315 * Returns: the allocated memory, or %NULL.
318 g_try_realloc (gpointer mem,
323 if (G_LIKELY (n_bytes))
324 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
329 glib_mem_vtable.free (mem);
332 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
338 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
342 * @n_blocks: the number of blocks to allocate
343 * @n_block_bytes: the size of each block in bytes
345 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
346 * but care is taken to detect possible overflow during multiplication.
349 * Returns: a pointer to the allocated memory
352 g_malloc_n (gsize n_blocks,
355 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
357 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
358 G_STRLOC, n_blocks, n_block_bytes);
361 return g_malloc (n_blocks * n_block_bytes);
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_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
370 * but care is taken to detect possible overflow during multiplication.
373 * Returns: a pointer to the allocated memory
376 g_malloc0_n (gsize n_blocks,
379 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
381 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
382 G_STRLOC, n_blocks, n_block_bytes);
385 return g_malloc0 (n_blocks * n_block_bytes);
390 * @mem: the memory to reallocate
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_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
395 * but care is taken to detect possible overflow during multiplication.
398 * Returns: the new address of the allocated memory
401 g_realloc_n (gpointer mem,
405 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
407 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
408 G_STRLOC, n_blocks, n_block_bytes);
411 return g_realloc (mem, n_blocks * n_block_bytes);
416 * @n_blocks: the number of blocks to allocate
417 * @n_block_bytes: the size of each block in bytes
419 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
420 * but care is taken to detect possible overflow during multiplication.
423 * Returns: the allocated memory, or %NULL.
426 g_try_malloc_n (gsize n_blocks,
429 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
432 return g_try_malloc (n_blocks * n_block_bytes);
437 * @n_blocks: the number of blocks to allocate
438 * @n_block_bytes: the size of each block in bytes
440 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
441 * but care is taken to detect possible overflow during multiplication.
444 * Returns: the allocated memory, or %NULL
447 g_try_malloc0_n (gsize n_blocks,
450 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
453 return g_try_malloc0 (n_blocks * n_block_bytes);
458 * @mem: previously-allocated memory, or %NULL.
459 * @n_blocks: the number of blocks to allocate
460 * @n_block_bytes: the size of each block in bytes
462 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
463 * but care is taken to detect possible overflow during multiplication.
466 * Returns: the allocated memory, or %NULL.
469 g_try_realloc_n (gpointer mem,
473 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
476 return g_try_realloc (mem, n_blocks * n_block_bytes);
482 fallback_calloc (gsize n_blocks,
485 gsize l = n_blocks * n_block_bytes;
486 gpointer mem = glib_mem_vtable.malloc (l);
494 static gboolean vtable_set = FALSE;
497 * g_mem_is_system_malloc
499 * Checks whether the allocator used by g_malloc() is the system's
500 * malloc implementation. If it returns %TRUE memory allocated with
501 * malloc() can be used interchangeable with memory allocated using g_malloc().
502 * This function is useful for avoiding an extra copy of allocated memory returned
503 * by a non-GLib-based API.
505 * A different allocator can be set using g_mem_set_vtable().
507 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
510 g_mem_is_system_malloc (void)
517 * @vtable: table of memory allocation routines.
519 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
520 * custom memory allocation routines. <emphasis>This function must be called
521 * before using any other GLib functions.</emphasis> The @vtable only needs to
522 * provide malloc(), realloc(), and free() functions; GLib can provide default
523 * implementations of the others. The malloc() and realloc() implementations
524 * should return %NULL on failure, GLib will handle error-checking for you.
525 * @vtable is copied, so need not persist after this function has been called.
528 g_mem_set_vtable (GMemVTable *vtable)
532 if (vtable->malloc && vtable->realloc && vtable->free)
534 glib_mem_vtable.malloc = vtable->malloc;
535 glib_mem_vtable.realloc = vtable->realloc;
536 glib_mem_vtable.free = vtable->free;
537 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
538 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
539 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
543 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
546 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
550 /* --- memory profiling and checking --- */
551 #ifdef G_DISABLE_CHECKS
553 * glib_mem_profiler_table:
555 * A #GMemVTable containing profiling variants of the memory
556 * allocation functions. Use them together with g_mem_profile()
557 * in order to get information about the memory allocation pattern
560 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
565 #else /* !G_DISABLE_CHECKS */
572 static guint *profile_data = NULL;
573 static gsize profile_allocs = 0;
574 static gsize profile_zinit = 0;
575 static gsize profile_frees = 0;
576 static GMutex gmem_profile_mutex;
577 #ifdef G_ENABLE_DEBUG
578 static volatile gsize g_trap_free_size = 0;
579 static volatile gsize g_trap_realloc_size = 0;
580 static volatile gsize g_trap_malloc_size = 0;
581 #endif /* G_ENABLE_DEBUG */
583 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
586 profiler_log (ProfilerJob job,
590 g_mutex_lock (&gmem_profile_mutex);
593 profile_data = standard_calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
594 sizeof (profile_data[0]));
595 if (!profile_data) /* memory system kiddin' me, eh? */
597 g_mutex_unlock (&gmem_profile_mutex);
602 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
603 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
604 (job & PROFILER_RELOC) != 0,
607 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
608 (job & PROFILER_RELOC) != 0,
612 if (job & PROFILER_ALLOC)
614 profile_allocs += n_bytes;
615 if (job & PROFILER_ZINIT)
616 profile_zinit += n_bytes;
619 profile_frees += n_bytes;
621 g_mutex_unlock (&gmem_profile_mutex);
625 profile_print_locked (guint *local_data,
628 gboolean need_header = TRUE;
631 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
633 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
634 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
635 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
636 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
638 if (!t_malloc && !t_realloc && !t_free && !t_refree)
640 else if (need_header)
643 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
644 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
645 g_print (" | malloc() | free() | realloc() | realloc() | \n");
646 g_print ("===========|============|============|============|============|===========\n");
648 if (i < MEM_PROFILE_TABLE_SIZE)
649 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
650 i, t_malloc, t_free, t_realloc, t_refree,
651 (t_malloc - t_free + t_realloc - t_refree) * i);
652 else if (i >= MEM_PROFILE_TABLE_SIZE)
653 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
654 i, t_malloc, t_free, t_realloc, t_refree);
657 g_print (" --- none ---\n");
664 * Outputs a summary of memory usage.
666 * It outputs the frequency of allocations of different sizes,
667 * the total number of bytes which have been allocated,
668 * the total number of bytes which have been freed,
669 * and the difference between the previous two values, i.e. the number of bytes
672 * Note that this function will not output anything unless you have
673 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
679 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
684 g_mutex_lock (&gmem_profile_mutex);
686 local_allocs = profile_allocs;
687 local_zinit = profile_zinit;
688 local_frees = profile_frees;
692 g_mutex_unlock (&gmem_profile_mutex);
696 memcpy (local_data, profile_data,
697 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
699 g_mutex_unlock (&gmem_profile_mutex);
701 g_print ("GLib Memory statistics (successful operations):\n");
702 profile_print_locked (local_data, TRUE);
703 g_print ("GLib Memory statistics (failing operations):\n");
704 profile_print_locked (local_data, FALSE);
705 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
706 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
707 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
708 "remaining=%"G_GSIZE_FORMAT"\n",
711 ((gdouble) local_zinit) / local_allocs * 100.0,
713 ((gdouble) local_frees) / local_allocs * 100.0,
714 local_allocs - local_frees);
718 profiler_try_malloc (gsize n_bytes)
722 #ifdef G_ENABLE_DEBUG
723 if (g_trap_malloc_size == n_bytes)
725 #endif /* G_ENABLE_DEBUG */
727 p = standard_malloc (sizeof (gsize) * 2 + n_bytes);
731 p[0] = 0; /* free count */
732 p[1] = n_bytes; /* length */
733 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
737 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
743 profiler_malloc (gsize n_bytes)
745 gpointer mem = profiler_try_malloc (n_bytes);
754 profiler_calloc (gsize n_blocks,
757 gsize l = n_blocks * n_block_bytes;
760 #ifdef G_ENABLE_DEBUG
761 if (g_trap_malloc_size == l)
763 #endif /* G_ENABLE_DEBUG */
765 p = standard_calloc (1, sizeof (gsize) * 2 + l);
769 p[0] = 0; /* free count */
770 p[1] = l; /* length */
771 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
776 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
784 profiler_free (gpointer mem)
789 if (p[0]) /* free count */
791 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
793 profiler_log (PROFILER_FREE,
799 #ifdef G_ENABLE_DEBUG
800 if (g_trap_free_size == p[1])
802 #endif /* G_ENABLE_DEBUG */
804 profiler_log (PROFILER_FREE,
807 memset (p + 2, 0xaa, p[1]);
809 /* for all those that miss standard_free (p); in this place, yes,
810 * we do leak all memory when profiling, and that is intentional
811 * to catch double frees. patch submissions are futile.
818 profiler_try_realloc (gpointer mem,
825 #ifdef G_ENABLE_DEBUG
826 if (g_trap_realloc_size == n_bytes)
828 #endif /* G_ENABLE_DEBUG */
830 if (mem && p[0]) /* free count */
832 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
833 "memory has been freed %"G_GSIZE_FORMAT" times already",
834 p + 2, (gsize) n_bytes, p[0]);
835 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
841 p = standard_realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
846 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
849 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
853 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
860 profiler_realloc (gpointer mem,
863 mem = profiler_try_realloc (mem, n_bytes);
871 static GMemVTable profiler_table = {
877 profiler_try_realloc,
879 GMemVTable *glib_mem_profiler_table = &profiler_table;
881 #endif /* !G_DISABLE_CHECKS */