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
));
257 * g_clear_pointer: (skip)
258 * @pp: a pointer to a variable, struct member etc. holding a pointer
259 * @destroy: a function to which a gpointer can be passed, to destroy *@pp
261 * Clears a reference to a variable.
263 * @pp must not be %NULL.
265 * If the reference is %NULL then this function does nothing.
266 * Otherwise, the variable is destroyed using @destroy and the
267 * pointer is set to %NULL.
269 * This function is threadsafe and modifies the pointer atomically,
270 * using memory barriers where needed.
272 * A macro is also included that allows this function to be used without
277 #undef g_clear_pointer
279 g_clear_pointer (gpointer
*pp
,
280 GDestroyNotify destroy
)
284 /* This is a little frustrating.
285 * Would be nice to have an atomic exchange (with no compare).
288 _p
= g_atomic_pointer_get (pp
);
289 while G_UNLIKELY (!g_atomic_pointer_compare_and_exchange (pp
, _p
, NULL
));
297 * @n_bytes: number of bytes to allocate.
299 * Attempts to allocate @n_bytes, and returns %NULL on failure.
300 * Contrast with g_malloc(), which aborts the program on failure.
302 * Returns: the allocated memory, or %NULL.
305 g_try_malloc (gsize n_bytes
)
309 if (G_LIKELY (n_bytes
))
310 mem
= glib_mem_vtable
.try_malloc (n_bytes
);
314 TRACE (GLIB_MEM_ALLOC((void*) mem
, (unsigned int) n_bytes
, 0, 1));
321 * @n_bytes: number of bytes to allocate
323 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
324 * failure. Contrast with g_malloc0(), which aborts the program on failure.
327 * Returns: the allocated memory, or %NULL
330 g_try_malloc0 (gsize n_bytes
)
334 if (G_LIKELY (n_bytes
))
335 mem
= glib_mem_vtable
.try_malloc (n_bytes
);
340 memset (mem
, 0, n_bytes
);
347 * @mem: (allow-none): previously-allocated memory, or %NULL.
348 * @n_bytes: number of bytes to allocate.
350 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
351 * on failure. Contrast with g_realloc(), which aborts the program
352 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
354 * Returns: the allocated memory, or %NULL.
357 g_try_realloc (gpointer mem
,
362 if (G_LIKELY (n_bytes
))
363 newmem
= glib_mem_vtable
.try_realloc (mem
, n_bytes
);
368 glib_mem_vtable
.free (mem
);
371 TRACE (GLIB_MEM_REALLOC((void*) newmem
, (void*)mem
, (unsigned int) n_bytes
, 1));
377 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
381 * @n_blocks: the number of blocks to allocate
382 * @n_block_bytes: the size of each block in bytes
384 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
385 * but care is taken to detect possible overflow during multiplication.
388 * Returns: a pointer to the allocated memory
391 g_malloc_n (gsize n_blocks
,
394 if (SIZE_OVERFLOWS (n_blocks
, n_block_bytes
))
396 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT
"*%"G_GSIZE_FORMAT
" bytes",
397 G_STRLOC
, n_blocks
, n_block_bytes
);
400 return g_malloc (n_blocks
* n_block_bytes
);
405 * @n_blocks: the number of blocks to allocate
406 * @n_block_bytes: the size of each block in bytes
408 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
409 * but care is taken to detect possible overflow during multiplication.
412 * Returns: a pointer to the allocated memory
415 g_malloc0_n (gsize n_blocks
,
418 if (SIZE_OVERFLOWS (n_blocks
, n_block_bytes
))
420 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT
"*%"G_GSIZE_FORMAT
" bytes",
421 G_STRLOC
, n_blocks
, n_block_bytes
);
424 return g_malloc0 (n_blocks
* n_block_bytes
);
429 * @mem: the memory to reallocate
430 * @n_blocks: the number of blocks to allocate
431 * @n_block_bytes: the size of each block in bytes
433 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
434 * but care is taken to detect possible overflow during multiplication.
437 * Returns: the new address of the allocated memory
440 g_realloc_n (gpointer mem
,
444 if (SIZE_OVERFLOWS (n_blocks
, n_block_bytes
))
446 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT
"*%"G_GSIZE_FORMAT
" bytes",
447 G_STRLOC
, n_blocks
, n_block_bytes
);
450 return g_realloc (mem
, n_blocks
* n_block_bytes
);
455 * @n_blocks: the number of blocks to allocate
456 * @n_block_bytes: the size of each block in bytes
458 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
459 * but care is taken to detect possible overflow during multiplication.
462 * Returns: the allocated memory, or %NULL.
465 g_try_malloc_n (gsize n_blocks
,
468 if (SIZE_OVERFLOWS (n_blocks
, n_block_bytes
))
471 return g_try_malloc (n_blocks
* n_block_bytes
);
476 * @n_blocks: the number of blocks to allocate
477 * @n_block_bytes: the size of each block in bytes
479 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
480 * but care is taken to detect possible overflow during multiplication.
483 * Returns: the allocated memory, or %NULL
486 g_try_malloc0_n (gsize n_blocks
,
489 if (SIZE_OVERFLOWS (n_blocks
, n_block_bytes
))
492 return g_try_malloc0 (n_blocks
* n_block_bytes
);
497 * @mem: (allow-none): previously-allocated memory, or %NULL.
498 * @n_blocks: the number of blocks to allocate
499 * @n_block_bytes: the size of each block in bytes
501 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
502 * but care is taken to detect possible overflow during multiplication.
505 * Returns: the allocated memory, or %NULL.
508 g_try_realloc_n (gpointer mem
,
512 if (SIZE_OVERFLOWS (n_blocks
, n_block_bytes
))
515 return g_try_realloc (mem
, n_blocks
* n_block_bytes
);
521 fallback_calloc (gsize n_blocks
,
524 gsize l
= n_blocks
* n_block_bytes
;
525 gpointer mem
= glib_mem_vtable
.malloc (l
);
533 static gboolean vtable_set
= FALSE
;
536 * g_mem_is_system_malloc:
538 * Checks whether the allocator used by g_malloc() is the system's
539 * malloc implementation. If it returns %TRUE memory allocated with
540 * malloc() can be used interchangeable with memory allocated using g_malloc().
541 * This function is useful for avoiding an extra copy of allocated memory returned
542 * by a non-GLib-based API.
544 * A different allocator can be set using g_mem_set_vtable().
546 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
549 g_mem_is_system_malloc (void)
556 * @vtable: table of memory allocation routines.
558 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
559 * custom memory allocation routines. <emphasis>This function must be called
560 * before using any other GLib functions.</emphasis> The @vtable only needs to
561 * provide malloc(), realloc(), and free() functions; GLib can provide default
562 * implementations of the others. The malloc() and realloc() implementations
563 * should return %NULL on failure, GLib will handle error-checking for you.
564 * @vtable is copied, so need not persist after this function has been called.
567 g_mem_set_vtable (GMemVTable
*vtable
)
571 if (vtable
->malloc
&& vtable
->realloc
&& vtable
->free
)
573 glib_mem_vtable
.malloc
= vtable
->malloc
;
574 glib_mem_vtable
.realloc
= vtable
->realloc
;
575 glib_mem_vtable
.free
= vtable
->free
;
576 glib_mem_vtable
.calloc
= vtable
->calloc
? vtable
->calloc
: fallback_calloc
;
577 glib_mem_vtable
.try_malloc
= vtable
->try_malloc
? vtable
->try_malloc
: glib_mem_vtable
.malloc
;
578 glib_mem_vtable
.try_realloc
= vtable
->try_realloc
? vtable
->try_realloc
: glib_mem_vtable
.realloc
;
582 g_warning (G_STRLOC
": memory allocation vtable lacks one of malloc(), realloc() or free()");
585 g_warning (G_STRLOC
": memory allocation vtable can only be set once at startup");
589 /* --- memory profiling and checking --- */
590 #ifdef G_DISABLE_CHECKS
592 * glib_mem_profiler_table:
594 * A #GMemVTable containing profiling variants of the memory
595 * allocation functions. Use them together with g_mem_profile()
596 * in order to get information about the memory allocation pattern
599 GMemVTable
*glib_mem_profiler_table
= &glib_mem_vtable
;
604 #else /* !G_DISABLE_CHECKS */
611 static guint
*profile_data
= NULL
;
612 static gsize profile_allocs
= 0;
613 static gsize profile_zinit
= 0;
614 static gsize profile_frees
= 0;
615 static GMutex gmem_profile_mutex
;
616 #ifdef G_ENABLE_DEBUG
617 static volatile gsize g_trap_free_size
= 0;
618 static volatile gsize g_trap_realloc_size
= 0;
619 static volatile gsize g_trap_malloc_size
= 0;
620 #endif /* G_ENABLE_DEBUG */
622 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
625 profiler_log (ProfilerJob job
,
629 g_mutex_lock (&gmem_profile_mutex
);
632 profile_data
= standard_calloc ((MEM_PROFILE_TABLE_SIZE
+ 1) * 8,
633 sizeof (profile_data
[0]));
634 if (!profile_data
) /* memory system kiddin' me, eh? */
636 g_mutex_unlock (&gmem_profile_mutex
);
641 if (n_bytes
< MEM_PROFILE_TABLE_SIZE
)
642 profile_data
[n_bytes
+ PROFILE_TABLE ((job
& PROFILER_ALLOC
) != 0,
643 (job
& PROFILER_RELOC
) != 0,
646 profile_data
[MEM_PROFILE_TABLE_SIZE
+ PROFILE_TABLE ((job
& PROFILER_ALLOC
) != 0,
647 (job
& PROFILER_RELOC
) != 0,
651 if (job
& PROFILER_ALLOC
)
653 profile_allocs
+= n_bytes
;
654 if (job
& PROFILER_ZINIT
)
655 profile_zinit
+= n_bytes
;
658 profile_frees
+= n_bytes
;
660 g_mutex_unlock (&gmem_profile_mutex
);
664 profile_print_locked (guint
*local_data
,
667 gboolean need_header
= TRUE
;
670 for (i
= 0; i
<= MEM_PROFILE_TABLE_SIZE
; i
++)
672 glong t_malloc
= local_data
[i
+ PROFILE_TABLE (1, 0, success
)];
673 glong t_realloc
= local_data
[i
+ PROFILE_TABLE (1, 1, success
)];
674 glong t_free
= local_data
[i
+ PROFILE_TABLE (0, 0, success
)];
675 glong t_refree
= local_data
[i
+ PROFILE_TABLE (0, 1, success
)];
677 if (!t_malloc
&& !t_realloc
&& !t_free
&& !t_refree
)
679 else if (need_header
)
682 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
683 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
684 g_print (" | malloc() | free() | realloc() | realloc() | \n");
685 g_print ("===========|============|============|============|============|===========\n");
687 if (i
< MEM_PROFILE_TABLE_SIZE
)
688 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
689 i
, t_malloc
, t_free
, t_realloc
, t_refree
,
690 (t_malloc
- t_free
+ t_realloc
- t_refree
) * i
);
691 else if (i
>= MEM_PROFILE_TABLE_SIZE
)
692 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
693 i
, t_malloc
, t_free
, t_realloc
, t_refree
);
696 g_print (" --- none ---\n");
702 * Outputs a summary of memory usage.
704 * It outputs the frequency of allocations of different sizes,
705 * the total number of bytes which have been allocated,
706 * the total number of bytes which have been freed,
707 * and the difference between the previous two values, i.e. the number of bytes
710 * Note that this function will not output anything unless you have
711 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
717 guint local_data
[(MEM_PROFILE_TABLE_SIZE
+ 1) * 8];
722 g_mutex_lock (&gmem_profile_mutex
);
724 local_allocs
= profile_allocs
;
725 local_zinit
= profile_zinit
;
726 local_frees
= profile_frees
;
730 g_mutex_unlock (&gmem_profile_mutex
);
734 memcpy (local_data
, profile_data
,
735 (MEM_PROFILE_TABLE_SIZE
+ 1) * 8 * sizeof (profile_data
[0]));
737 g_mutex_unlock (&gmem_profile_mutex
);
739 g_print ("GLib Memory statistics (successful operations):\n");
740 profile_print_locked (local_data
, TRUE
);
741 g_print ("GLib Memory statistics (failing operations):\n");
742 profile_print_locked (local_data
, FALSE
);
743 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT
", "
744 "zero-initialized=%"G_GSIZE_FORMAT
" (%.2f%%), "
745 "freed=%"G_GSIZE_FORMAT
" (%.2f%%), "
746 "remaining=%"G_GSIZE_FORMAT
"\n",
749 ((gdouble
) local_zinit
) / local_allocs
* 100.0,
751 ((gdouble
) local_frees
) / local_allocs
* 100.0,
752 local_allocs
- local_frees
);
756 profiler_try_malloc (gsize n_bytes
)
760 #ifdef G_ENABLE_DEBUG
761 if (g_trap_malloc_size
== n_bytes
)
763 #endif /* G_ENABLE_DEBUG */
765 p
= standard_malloc (sizeof (gsize
) * 2 + n_bytes
);
769 p
[0] = 0; /* free count */
770 p
[1] = n_bytes
; /* length */
771 profiler_log (PROFILER_ALLOC
, n_bytes
, TRUE
);
775 profiler_log (PROFILER_ALLOC
, n_bytes
, FALSE
);
781 profiler_malloc (gsize n_bytes
)
783 gpointer mem
= profiler_try_malloc (n_bytes
);
792 profiler_calloc (gsize n_blocks
,
795 gsize l
= n_blocks
* n_block_bytes
;
798 #ifdef G_ENABLE_DEBUG
799 if (g_trap_malloc_size
== l
)
801 #endif /* G_ENABLE_DEBUG */
803 p
= standard_calloc (1, sizeof (gsize
) * 2 + l
);
807 p
[0] = 0; /* free count */
808 p
[1] = l
; /* length */
809 profiler_log (PROFILER_ALLOC
| PROFILER_ZINIT
, l
, TRUE
);
814 profiler_log (PROFILER_ALLOC
| PROFILER_ZINIT
, l
, FALSE
);
822 profiler_free (gpointer mem
)
827 if (p
[0]) /* free count */
829 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT
" times already",
831 profiler_log (PROFILER_FREE
,
837 #ifdef G_ENABLE_DEBUG
838 if (g_trap_free_size
== p
[1])
840 #endif /* G_ENABLE_DEBUG */
842 profiler_log (PROFILER_FREE
,
845 memset (p
+ 2, 0xaa, p
[1]);
847 /* for all those that miss standard_free (p); in this place, yes,
848 * we do leak all memory when profiling, and that is intentional
849 * to catch double frees. patch submissions are futile.
856 profiler_try_realloc (gpointer mem
,
863 #ifdef G_ENABLE_DEBUG
864 if (g_trap_realloc_size
== n_bytes
)
866 #endif /* G_ENABLE_DEBUG */
868 if (mem
&& p
[0]) /* free count */
870 g_warning ("realloc(%p, %"G_GSIZE_FORMAT
"): "
871 "memory has been freed %"G_GSIZE_FORMAT
" times already",
872 p
+ 2, (gsize
) n_bytes
, p
[0]);
873 profiler_log (PROFILER_ALLOC
| PROFILER_RELOC
, n_bytes
, FALSE
);
879 p
= standard_realloc (mem
? p
: NULL
, sizeof (gsize
) * 2 + n_bytes
);
884 profiler_log (PROFILER_FREE
| PROFILER_RELOC
, p
[1], TRUE
);
887 profiler_log (PROFILER_ALLOC
| PROFILER_RELOC
, p
[1], TRUE
);
891 profiler_log (PROFILER_ALLOC
| PROFILER_RELOC
, n_bytes
, FALSE
);
898 profiler_realloc (gpointer mem
,
901 mem
= profiler_try_realloc (mem
, n_bytes
);
909 static GMemVTable profiler_table
= {
915 profiler_try_realloc
,
917 GMemVTable
*glib_mem_profiler_table
= &profiler_table
;
919 #endif /* !G_DISABLE_CHECKS */