Remove redundant header inclusions
[glib.git] / glib / gmem.c
blob7212ae49db5013d1250738f62d66a3477a4248a2
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/.
27 /*
28 * MT safe
31 #include "config.h"
33 #include "gmem.h"
35 #include <stdlib.h>
36 #include <string.h>
37 #include <signal.h>
39 #include "gbacktrace.h"
40 #include "gtestutils.h"
41 #include "gthread.h"
42 #include "glib_trace.h"
45 #define MEM_PROFILE_TABLE_SIZE 4096
48 /* notes on macros:
49 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
50 * g_mem_profile().
51 * REALLOC_0_WORKS is defined if g_realloc (NULL, x) works.
52 * SANE_MALLOC_PROTOS is defined if the systems malloc() and friends functions
53 * match the corresponding GLib prototypes, keep configure.ac and gmem.h in sync here.
54 * g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
57 /* --- prototypes --- */
58 static gboolean g_mem_initialized = FALSE;
59 static void g_mem_init_nomessage (void);
62 /* --- malloc wrappers --- */
63 #ifndef REALLOC_0_WORKS
64 static gpointer
65 standard_realloc (gpointer mem,
66 gsize n_bytes)
68 if (!mem)
69 return malloc (n_bytes);
70 else
71 return realloc (mem, n_bytes);
73 #endif /* !REALLOC_0_WORKS */
75 #ifdef SANE_MALLOC_PROTOS
76 # define standard_malloc malloc
77 # ifdef REALLOC_0_WORKS
78 # define standard_realloc realloc
79 # endif /* REALLOC_0_WORKS */
80 # define standard_free free
81 # define standard_calloc calloc
82 # define standard_try_malloc malloc
83 # define standard_try_realloc realloc
84 #else /* !SANE_MALLOC_PROTOS */
85 static gpointer
86 standard_malloc (gsize n_bytes)
88 return malloc (n_bytes);
90 # ifdef REALLOC_0_WORKS
91 static gpointer
92 standard_realloc (gpointer mem,
93 gsize n_bytes)
95 return realloc (mem, n_bytes);
97 # endif /* REALLOC_0_WORKS */
98 static void
99 standard_free (gpointer mem)
101 free (mem);
103 static gpointer
104 standard_calloc (gsize n_blocks,
105 gsize n_bytes)
107 return calloc (n_blocks, n_bytes);
109 #define standard_try_malloc standard_malloc
110 #define standard_try_realloc standard_realloc
111 #endif /* !SANE_MALLOC_PROTOS */
114 /* --- variables --- */
115 static GMemVTable glib_mem_vtable = {
116 standard_malloc,
117 standard_realloc,
118 standard_free,
119 standard_calloc,
120 standard_try_malloc,
121 standard_try_realloc,
125 * SECTION:memory
126 * @Short_Description: general memory-handling
127 * @Title: Memory Allocation
129 * These functions provide support for allocating and freeing memory.
131 * <note>
132 * If any call to allocate memory fails, the application is terminated.
133 * This also means that there is no need to check if the call succeeded.
134 * </note>
136 * <note>
137 * It's important to match g_malloc() with g_free(), plain malloc() with free(),
138 * and (if you're using C++) new with delete and new[] with delete[]. Otherwise
139 * bad things can happen, since these allocators may use different memory
140 * pools (and new/delete call constructors and destructors). See also
141 * g_mem_set_vtable().
142 * </note>
145 /* --- functions --- */
147 * g_malloc:
148 * @n_bytes: the number of bytes to allocate
150 * Allocates @n_bytes bytes of memory.
151 * If @n_bytes is 0 it returns %NULL.
153 * Returns: a pointer to the allocated memory
155 gpointer
156 g_malloc (gsize n_bytes)
158 if (G_UNLIKELY (!g_mem_initialized))
159 g_mem_init_nomessage();
160 if (G_LIKELY (n_bytes))
162 gpointer mem;
164 mem = glib_mem_vtable.malloc (n_bytes);
165 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
166 if (mem)
167 return mem;
169 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
170 G_STRLOC, n_bytes);
173 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
175 return NULL;
179 * g_malloc0:
180 * @n_bytes: the number of bytes to allocate
182 * Allocates @n_bytes bytes of memory, initialized to 0's.
183 * If @n_bytes is 0 it returns %NULL.
185 * Returns: a pointer to the allocated memory
187 gpointer
188 g_malloc0 (gsize n_bytes)
190 if (G_UNLIKELY (!g_mem_initialized))
191 g_mem_init_nomessage();
192 if (G_LIKELY (n_bytes))
194 gpointer mem;
196 mem = glib_mem_vtable.calloc (1, n_bytes);
197 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
198 if (mem)
199 return mem;
201 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
202 G_STRLOC, n_bytes);
205 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
207 return NULL;
211 * g_realloc:
212 * @mem: the memory to reallocate
213 * @n_bytes: new size of the memory in bytes
215 * Reallocates the memory pointed to by @mem, so that it now has space for
216 * @n_bytes bytes of memory. It returns the new address of the memory, which may
217 * have been moved. @mem may be %NULL, in which case it's considered to
218 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
219 * and @mem will be freed unless it is %NULL.
221 * Returns: the new address of the allocated memory
223 gpointer
224 g_realloc (gpointer mem,
225 gsize n_bytes)
227 gpointer newmem;
229 if (G_UNLIKELY (!g_mem_initialized))
230 g_mem_init_nomessage();
231 if (G_LIKELY (n_bytes))
233 newmem = glib_mem_vtable.realloc (mem, n_bytes);
234 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
235 if (newmem)
236 return newmem;
238 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
239 G_STRLOC, n_bytes);
242 if (mem)
243 glib_mem_vtable.free (mem);
245 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
247 return NULL;
251 * g_free:
252 * @mem: the memory to free
254 * Frees the memory pointed to by @mem.
255 * If @mem is %NULL it simply returns.
257 void
258 g_free (gpointer mem)
260 if (G_UNLIKELY (!g_mem_initialized))
261 g_mem_init_nomessage();
262 if (G_LIKELY (mem))
263 glib_mem_vtable.free (mem);
264 TRACE(GLIB_MEM_FREE((void*) mem));
268 * g_try_malloc:
269 * @n_bytes: number of bytes to allocate.
271 * Attempts to allocate @n_bytes, and returns %NULL on failure.
272 * Contrast with g_malloc(), which aborts the program on failure.
274 * Returns: the allocated memory, or %NULL.
276 gpointer
277 g_try_malloc (gsize n_bytes)
279 gpointer mem;
281 if (G_UNLIKELY (!g_mem_initialized))
282 g_mem_init_nomessage();
283 if (G_LIKELY (n_bytes))
284 mem = glib_mem_vtable.try_malloc (n_bytes);
285 else
286 mem = NULL;
288 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
290 return mem;
294 * g_try_malloc0:
295 * @n_bytes: number of bytes to allocate
297 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
298 * failure. Contrast with g_malloc0(), which aborts the program on failure.
300 * Since: 2.8
301 * Returns: the allocated memory, or %NULL
303 gpointer
304 g_try_malloc0 (gsize n_bytes)
306 gpointer mem;
308 if (G_UNLIKELY (!g_mem_initialized))
309 g_mem_init_nomessage();
310 if (G_LIKELY (n_bytes))
311 mem = glib_mem_vtable.try_malloc (n_bytes);
312 else
313 mem = NULL;
315 if (mem)
316 memset (mem, 0, n_bytes);
318 return mem;
322 * g_try_realloc:
323 * @mem: previously-allocated memory, or %NULL.
324 * @n_bytes: number of bytes to allocate.
326 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
327 * on failure. Contrast with g_realloc(), which aborts the program
328 * on failure. If @mem is %NULL, behaves the same as g_try_malloc().
330 * Returns: the allocated memory, or %NULL.
332 gpointer
333 g_try_realloc (gpointer mem,
334 gsize n_bytes)
336 gpointer newmem;
338 if (G_UNLIKELY (!g_mem_initialized))
339 g_mem_init_nomessage();
340 if (G_LIKELY (n_bytes))
341 newmem = glib_mem_vtable.try_realloc (mem, n_bytes);
342 else
344 newmem = NULL;
345 if (mem)
346 glib_mem_vtable.free (mem);
349 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
351 return newmem;
355 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
358 * g_malloc_n:
359 * @n_blocks: the number of blocks to allocate
360 * @n_block_bytes: the size of each block in bytes
362 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
363 * but care is taken to detect possible overflow during multiplication.
365 * Since: 2.24
366 * Returns: a pointer to the allocated memory
368 gpointer
369 g_malloc_n (gsize n_blocks,
370 gsize n_block_bytes)
372 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
374 if (G_UNLIKELY (!g_mem_initialized))
375 g_mem_init_nomessage();
377 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
378 G_STRLOC, n_blocks, n_block_bytes);
381 return g_malloc (n_blocks * n_block_bytes);
385 * g_malloc0_n:
386 * @n_blocks: the number of blocks to allocate
387 * @n_block_bytes: the size of each block in bytes
389 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
390 * but care is taken to detect possible overflow during multiplication.
392 * Since: 2.24
393 * Returns: a pointer to the allocated memory
395 gpointer
396 g_malloc0_n (gsize n_blocks,
397 gsize n_block_bytes)
399 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
401 if (G_UNLIKELY (!g_mem_initialized))
402 g_mem_init_nomessage();
404 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
405 G_STRLOC, n_blocks, n_block_bytes);
408 return g_malloc0 (n_blocks * n_block_bytes);
412 * g_realloc_n:
413 * @mem: the memory to reallocate
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_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
418 * but care is taken to detect possible overflow during multiplication.
420 * Since: 2.24
421 * Returns: the new address of the allocated memory
423 gpointer
424 g_realloc_n (gpointer mem,
425 gsize n_blocks,
426 gsize n_block_bytes)
428 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
430 if (G_UNLIKELY (!g_mem_initialized))
431 g_mem_init_nomessage();
433 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
434 G_STRLOC, n_blocks, n_block_bytes);
437 return g_realloc (mem, n_blocks * n_block_bytes);
441 * g_try_malloc_n:
442 * @n_blocks: the number of blocks to allocate
443 * @n_block_bytes: the size of each block in bytes
445 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
446 * but care is taken to detect possible overflow during multiplication.
448 * Since: 2.24
449 * Returns: the allocated memory, or %NULL.
451 gpointer
452 g_try_malloc_n (gsize n_blocks,
453 gsize n_block_bytes)
455 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
456 return NULL;
458 return g_try_malloc (n_blocks * n_block_bytes);
462 * g_try_malloc0_n:
463 * @n_blocks: the number of blocks to allocate
464 * @n_block_bytes: the size of each block in bytes
466 * This function is similar to g_try_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
467 * but care is taken to detect possible overflow during multiplication.
469 * Since: 2.24
470 * Returns: the allocated memory, or %NULL
472 gpointer
473 g_try_malloc0_n (gsize n_blocks,
474 gsize n_block_bytes)
476 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
477 return NULL;
479 return g_try_malloc0 (n_blocks * n_block_bytes);
483 * g_try_realloc_n:
484 * @mem: previously-allocated memory, or %NULL.
485 * @n_blocks: the number of blocks to allocate
486 * @n_block_bytes: the size of each block in bytes
488 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
489 * but care is taken to detect possible overflow during multiplication.
491 * Since: 2.24
492 * Returns: the allocated memory, or %NULL.
494 gpointer
495 g_try_realloc_n (gpointer mem,
496 gsize n_blocks,
497 gsize n_block_bytes)
499 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
500 return NULL;
502 return g_try_realloc (mem, n_blocks * n_block_bytes);
507 static gpointer
508 fallback_calloc (gsize n_blocks,
509 gsize n_block_bytes)
511 gsize l = n_blocks * n_block_bytes;
512 gpointer mem = glib_mem_vtable.malloc (l);
514 if (mem)
515 memset (mem, 0, l);
517 return mem;
520 static gboolean vtable_set = FALSE;
523 * g_mem_is_system_malloc
525 * Checks whether the allocator used by g_malloc() is the system's
526 * malloc implementation. If it returns %TRUE memory allocated with
527 * malloc() can be used interchangeable with memory allocated using g_malloc().
528 * This function is useful for avoiding an extra copy of allocated memory returned
529 * by a non-GLib-based API.
531 * A different allocator can be set using g_mem_set_vtable().
533 * Return value: if %TRUE, malloc() and g_malloc() can be mixed.
535 gboolean
536 g_mem_is_system_malloc (void)
538 return !vtable_set;
542 * g_mem_set_vtable:
543 * @vtable: table of memory allocation routines.
545 * Sets the #GMemVTable to use for memory allocation. You can use this to provide
546 * custom memory allocation routines. <emphasis>This function must be called
547 * before using any other GLib functions.</emphasis> The @vtable only needs to
548 * provide malloc(), realloc(), and free() functions; GLib can provide default
549 * implementations of the others. The malloc() and realloc() implementations
550 * should return %NULL on failure, GLib will handle error-checking for you.
551 * @vtable is copied, so need not persist after this function has been called.
553 void
554 g_mem_set_vtable (GMemVTable *vtable)
556 if (!vtable_set)
558 if (vtable->malloc && vtable->realloc && vtable->free)
560 glib_mem_vtable.malloc = vtable->malloc;
561 glib_mem_vtable.realloc = vtable->realloc;
562 glib_mem_vtable.free = vtable->free;
563 glib_mem_vtable.calloc = vtable->calloc ? vtable->calloc : fallback_calloc;
564 glib_mem_vtable.try_malloc = vtable->try_malloc ? vtable->try_malloc : glib_mem_vtable.malloc;
565 glib_mem_vtable.try_realloc = vtable->try_realloc ? vtable->try_realloc : glib_mem_vtable.realloc;
566 vtable_set = TRUE;
568 else
569 g_warning (G_STRLOC ": memory allocation vtable lacks one of malloc(), realloc() or free()");
571 else
572 g_warning (G_STRLOC ": memory allocation vtable can only be set once at startup");
576 /* --- memory profiling and checking --- */
577 #ifdef G_DISABLE_CHECKS
579 * glib_mem_profiler_table:
581 * A #GMemVTable containing profiling variants of the memory
582 * allocation functions. Use them together with g_mem_profile()
583 * in order to get information about the memory allocation pattern
584 * of your program.
586 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
587 void
588 g_mem_profile (void)
591 #else /* !G_DISABLE_CHECKS */
592 typedef enum {
593 PROFILER_FREE = 0,
594 PROFILER_ALLOC = 1,
595 PROFILER_RELOC = 2,
596 PROFILER_ZINIT = 4
597 } ProfilerJob;
598 static guint *profile_data = NULL;
599 static gsize profile_allocs = 0;
600 static gsize profile_zinit = 0;
601 static gsize profile_frees = 0;
602 static GMutex *gmem_profile_mutex = NULL;
603 #ifdef G_ENABLE_DEBUG
604 static volatile gsize g_trap_free_size = 0;
605 static volatile gsize g_trap_realloc_size = 0;
606 static volatile gsize g_trap_malloc_size = 0;
607 #endif /* G_ENABLE_DEBUG */
609 #define PROFILE_TABLE(f1,f2,f3) ( ( ((f3) << 2) | ((f2) << 1) | (f1) ) * (MEM_PROFILE_TABLE_SIZE + 1))
611 static void
612 profiler_log (ProfilerJob job,
613 gsize n_bytes,
614 gboolean success)
616 g_mutex_lock (gmem_profile_mutex);
617 if (!profile_data)
619 profile_data = standard_calloc ((MEM_PROFILE_TABLE_SIZE + 1) * 8,
620 sizeof (profile_data[0]));
621 if (!profile_data) /* memory system kiddin' me, eh? */
623 g_mutex_unlock (gmem_profile_mutex);
624 return;
628 if (n_bytes < MEM_PROFILE_TABLE_SIZE)
629 profile_data[n_bytes + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
630 (job & PROFILER_RELOC) != 0,
631 success != 0)] += 1;
632 else
633 profile_data[MEM_PROFILE_TABLE_SIZE + PROFILE_TABLE ((job & PROFILER_ALLOC) != 0,
634 (job & PROFILER_RELOC) != 0,
635 success != 0)] += 1;
636 if (success)
638 if (job & PROFILER_ALLOC)
640 profile_allocs += n_bytes;
641 if (job & PROFILER_ZINIT)
642 profile_zinit += n_bytes;
644 else
645 profile_frees += n_bytes;
647 g_mutex_unlock (gmem_profile_mutex);
650 static void
651 profile_print_locked (guint *local_data,
652 gboolean success)
654 gboolean need_header = TRUE;
655 guint i;
657 for (i = 0; i <= MEM_PROFILE_TABLE_SIZE; i++)
659 glong t_malloc = local_data[i + PROFILE_TABLE (1, 0, success)];
660 glong t_realloc = local_data[i + PROFILE_TABLE (1, 1, success)];
661 glong t_free = local_data[i + PROFILE_TABLE (0, 0, success)];
662 glong t_refree = local_data[i + PROFILE_TABLE (0, 1, success)];
664 if (!t_malloc && !t_realloc && !t_free && !t_refree)
665 continue;
666 else if (need_header)
668 need_header = FALSE;
669 g_print (" blocks of | allocated | freed | allocated | freed | n_bytes \n");
670 g_print (" n_bytes | n_times by | n_times by | n_times by | n_times by | remaining \n");
671 g_print (" | malloc() | free() | realloc() | realloc() | \n");
672 g_print ("===========|============|============|============|============|===========\n");
674 if (i < MEM_PROFILE_TABLE_SIZE)
675 g_print ("%10u | %10ld | %10ld | %10ld | %10ld |%+11ld\n",
676 i, t_malloc, t_free, t_realloc, t_refree,
677 (t_malloc - t_free + t_realloc - t_refree) * i);
678 else if (i >= MEM_PROFILE_TABLE_SIZE)
679 g_print (" >%6u | %10ld | %10ld | %10ld | %10ld | ***\n",
680 i, t_malloc, t_free, t_realloc, t_refree);
682 if (need_header)
683 g_print (" --- none ---\n");
687 * g_mem_profile:
688 * @void:
690 * Outputs a summary of memory usage.
692 * It outputs the frequency of allocations of different sizes,
693 * the total number of bytes which have been allocated,
694 * the total number of bytes which have been freed,
695 * and the difference between the previous two values, i.e. the number of bytes
696 * still in use.
698 * Note that this function will not output anything unless you have
699 * previously installed the #glib_mem_profiler_table with g_mem_set_vtable().
702 void
703 g_mem_profile (void)
705 guint local_data[(MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0])];
706 gsize local_allocs;
707 gsize local_zinit;
708 gsize local_frees;
710 if (G_UNLIKELY (!g_mem_initialized))
711 g_mem_init_nomessage();
713 g_mutex_lock (gmem_profile_mutex);
715 local_allocs = profile_allocs;
716 local_zinit = profile_zinit;
717 local_frees = profile_frees;
719 if (!profile_data)
721 g_mutex_unlock (gmem_profile_mutex);
722 return;
725 memcpy (local_data, profile_data,
726 (MEM_PROFILE_TABLE_SIZE + 1) * 8 * sizeof (profile_data[0]));
728 g_mutex_unlock (gmem_profile_mutex);
730 g_print ("GLib Memory statistics (successful operations):\n");
731 profile_print_locked (local_data, TRUE);
732 g_print ("GLib Memory statistics (failing operations):\n");
733 profile_print_locked (local_data, FALSE);
734 g_print ("Total bytes: allocated=%"G_GSIZE_FORMAT", "
735 "zero-initialized=%"G_GSIZE_FORMAT" (%.2f%%), "
736 "freed=%"G_GSIZE_FORMAT" (%.2f%%), "
737 "remaining=%"G_GSIZE_FORMAT"\n",
738 local_allocs,
739 local_zinit,
740 ((gdouble) local_zinit) / local_allocs * 100.0,
741 local_frees,
742 ((gdouble) local_frees) / local_allocs * 100.0,
743 local_allocs - local_frees);
746 static gpointer
747 profiler_try_malloc (gsize n_bytes)
749 gsize *p;
751 #ifdef G_ENABLE_DEBUG
752 if (g_trap_malloc_size == n_bytes)
753 G_BREAKPOINT ();
754 #endif /* G_ENABLE_DEBUG */
756 p = standard_malloc (sizeof (gsize) * 2 + n_bytes);
758 if (p)
760 p[0] = 0; /* free count */
761 p[1] = n_bytes; /* length */
762 profiler_log (PROFILER_ALLOC, n_bytes, TRUE);
763 p += 2;
765 else
766 profiler_log (PROFILER_ALLOC, n_bytes, FALSE);
768 return p;
771 static gpointer
772 profiler_malloc (gsize n_bytes)
774 gpointer mem = profiler_try_malloc (n_bytes);
776 if (!mem)
777 g_mem_profile ();
779 return mem;
782 static gpointer
783 profiler_calloc (gsize n_blocks,
784 gsize n_block_bytes)
786 gsize l = n_blocks * n_block_bytes;
787 gsize *p;
789 #ifdef G_ENABLE_DEBUG
790 if (g_trap_malloc_size == l)
791 G_BREAKPOINT ();
792 #endif /* G_ENABLE_DEBUG */
794 p = standard_calloc (1, sizeof (gsize) * 2 + l);
796 if (p)
798 p[0] = 0; /* free count */
799 p[1] = l; /* length */
800 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, TRUE);
801 p += 2;
803 else
805 profiler_log (PROFILER_ALLOC | PROFILER_ZINIT, l, FALSE);
806 g_mem_profile ();
809 return p;
812 static void
813 profiler_free (gpointer mem)
815 gsize *p = mem;
817 p -= 2;
818 if (p[0]) /* free count */
820 g_warning ("free(%p): memory has been freed %"G_GSIZE_FORMAT" times already",
821 p + 2, p[0]);
822 profiler_log (PROFILER_FREE,
823 p[1], /* length */
824 FALSE);
826 else
828 #ifdef G_ENABLE_DEBUG
829 if (g_trap_free_size == p[1])
830 G_BREAKPOINT ();
831 #endif /* G_ENABLE_DEBUG */
833 profiler_log (PROFILER_FREE,
834 p[1], /* length */
835 TRUE);
836 memset (p + 2, 0xaa, p[1]);
838 /* for all those that miss standard_free (p); in this place, yes,
839 * we do leak all memory when profiling, and that is intentional
840 * to catch double frees. patch submissions are futile.
843 p[0] += 1;
846 static gpointer
847 profiler_try_realloc (gpointer mem,
848 gsize n_bytes)
850 gsize *p = mem;
852 p -= 2;
854 #ifdef G_ENABLE_DEBUG
855 if (g_trap_realloc_size == n_bytes)
856 G_BREAKPOINT ();
857 #endif /* G_ENABLE_DEBUG */
859 if (mem && p[0]) /* free count */
861 g_warning ("realloc(%p, %"G_GSIZE_FORMAT"): "
862 "memory has been freed %"G_GSIZE_FORMAT" times already",
863 p + 2, (gsize) n_bytes, p[0]);
864 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
866 return NULL;
868 else
870 p = standard_realloc (mem ? p : NULL, sizeof (gsize) * 2 + n_bytes);
872 if (p)
874 if (mem)
875 profiler_log (PROFILER_FREE | PROFILER_RELOC, p[1], TRUE);
876 p[0] = 0;
877 p[1] = n_bytes;
878 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, p[1], TRUE);
879 p += 2;
881 else
882 profiler_log (PROFILER_ALLOC | PROFILER_RELOC, n_bytes, FALSE);
884 return p;
888 static gpointer
889 profiler_realloc (gpointer mem,
890 gsize n_bytes)
892 mem = profiler_try_realloc (mem, n_bytes);
894 if (!mem)
895 g_mem_profile ();
897 return mem;
900 static GMemVTable profiler_table = {
901 profiler_malloc,
902 profiler_realloc,
903 profiler_free,
904 profiler_calloc,
905 profiler_try_malloc,
906 profiler_try_realloc,
908 GMemVTable *glib_mem_profiler_table = &profiler_table;
910 #endif /* !G_DISABLE_CHECKS */
912 /* --- MemChunks --- */
914 * SECTION: allocators
915 * @title: Memory Allocators
916 * @short_description: deprecated way to allocate chunks of memory for
917 * GList, GSList and GNode
919 * Prior to 2.10, #GAllocator was used as an efficient way to allocate
920 * small pieces of memory for use with the #GList, #GSList and #GNode
921 * data structures. Since 2.10, it has been completely replaced by the
922 * <link linkend="glib-Memory-Slices">slice allocator</link> and
923 * deprecated.
927 * SECTION: memory_chunks
928 * @title: Memory Chunks
929 * @short_description: deprecated way to allocate groups of equal-sized
930 * chunks of memory
932 * Memory chunks provide an space-efficient way to allocate equal-sized
933 * pieces of memory, called atoms. However, due to the administrative
934 * overhead (in particular for #G_ALLOC_AND_FREE, and when used from
935 * multiple threads), they are in practise often slower than direct use
936 * of g_malloc(). Therefore, memory chunks have been deprecated in
937 * favor of the <link linkend="glib-Memory-Slices">slice
938 * allocator</link>, which has been added in 2.10. All internal uses of
939 * memory chunks in GLib have been converted to the
940 * <literal>g_slice</literal> API.
942 * There are two types of memory chunks, #G_ALLOC_ONLY, and
943 * #G_ALLOC_AND_FREE. <itemizedlist> <listitem><para> #G_ALLOC_ONLY
944 * chunks only allow allocation of atoms. The atoms can never be freed
945 * individually. The memory chunk can only be free in its entirety.
946 * </para></listitem> <listitem><para> #G_ALLOC_AND_FREE chunks do
947 * allow atoms to be freed individually. The disadvantage of this is
948 * that the memory chunk has to keep track of which atoms have been
949 * freed. This results in more memory being used and a slight
950 * degradation in performance. </para></listitem> </itemizedlist>
952 * To create a memory chunk use g_mem_chunk_new() or the convenience
953 * macro g_mem_chunk_create().
955 * To allocate a new atom use g_mem_chunk_alloc(),
956 * g_mem_chunk_alloc0(), or the convenience macros g_chunk_new() or
957 * g_chunk_new0().
959 * To free an atom use g_mem_chunk_free(), or the convenience macro
960 * g_chunk_free(). (Atoms can only be freed if the memory chunk is
961 * created with the type set to #G_ALLOC_AND_FREE.)
963 * To free any blocks of memory which are no longer being used, use
964 * g_mem_chunk_clean(). To clean all memory chunks, use g_blow_chunks().
966 * To reset the memory chunk, freeing all of the atoms, use
967 * g_mem_chunk_reset().
969 * To destroy a memory chunk, use g_mem_chunk_destroy().
971 * To help debug memory chunks, use g_mem_chunk_info() and
972 * g_mem_chunk_print().
974 * <example>
975 * <title>Using a #GMemChunk</title>
976 * <programlisting>
977 * GMemChunk *mem_chunk;
978 * gchar *mem[10000];
979 * gint i;
981 * /<!-- -->* Create a GMemChunk with atoms 50 bytes long, and memory
982 * blocks holding 100 bytes. Note that this means that only 2 atoms
983 * fit into each memory block and so isn't very efficient. *<!-- -->/
984 * mem_chunk = g_mem_chunk_new ("test mem chunk", 50, 100, G_ALLOC_AND_FREE);
985 * /<!-- -->* Now allocate 10000 atoms. *<!-- -->/
986 * for (i = 0; i &lt; 10000; i++)
988 * mem[i] = g_chunk_new (gchar, mem_chunk);
989 * /<!-- -->* Fill in the atom memory with some junk. *<!-- -->/
990 * for (j = 0; j &lt; 50; j++)
991 * mem[i][j] = i * j;
993 * /<!-- -->* Now free all of the atoms. Note that since we are going to
994 * destroy the GMemChunk, this wouldn't normally be used. *<!-- -->/
995 * for (i = 0; i &lt; 10000; i++)
997 * g_mem_chunk_free (mem_chunk, mem[i]);
999 * /<!-- -->* We are finished with the GMemChunk, so we destroy it. *<!-- -->/
1000 * g_mem_chunk_destroy (mem_chunk);
1001 * </programlisting>
1002 * </example>
1004 * <example>
1005 * <title>Using a #GMemChunk with data structures</title>
1006 * <programlisting>
1007 * GMemChunk *array_mem_chunk;
1008 * GRealArray *array;
1009 * /<!-- -->* Create a GMemChunk to hold GRealArray structures, using
1010 * the g_mem_chunk_create(<!-- -->) convenience macro. We want 1024 atoms in each
1011 * memory block, and we want to be able to free individual atoms. *<!-- -->/
1012 * array_mem_chunk = g_mem_chunk_create (GRealArray, 1024, G_ALLOC_AND_FREE);
1013 * /<!-- -->* Allocate one atom, using the g_chunk_new(<!-- -->) convenience macro. *<!-- -->/
1014 * array = g_chunk_new (GRealArray, array_mem_chunk);
1015 * /<!-- -->* We can now use array just like a normal pointer to a structure. *<!-- -->/
1016 * array->data = NULL;
1017 * array->len = 0;
1018 * array->alloc = 0;
1019 * array->zero_terminated = (zero_terminated ? 1 : 0);
1020 * array->clear = (clear ? 1 : 0);
1021 * array->elt_size = elt_size;
1022 * /<!-- -->* We can free the element, so it can be reused. *<!-- -->/
1023 * g_chunk_free (array, array_mem_chunk);
1024 * /<!-- -->* We destroy the GMemChunk when we are finished with it. *<!-- -->/
1025 * g_mem_chunk_destroy (array_mem_chunk);
1026 * </programlisting>
1027 * </example>
1030 #ifndef G_ALLOC_AND_FREE
1033 * GAllocator:
1035 * The #GAllocator struct contains private data. and should only be
1036 * accessed using the following functions.
1038 typedef struct _GAllocator GAllocator;
1041 * GMemChunk:
1043 * The #GMemChunk struct is an opaque data structure representing a
1044 * memory chunk. It should be accessed only through the use of the
1045 * following functions.
1047 typedef struct _GMemChunk GMemChunk;
1050 * G_ALLOC_ONLY:
1052 * Specifies the type of a #GMemChunk. Used in g_mem_chunk_new() and
1053 * g_mem_chunk_create() to specify that atoms will never be freed
1054 * individually.
1056 #define G_ALLOC_ONLY 1
1059 * G_ALLOC_AND_FREE:
1061 * Specifies the type of a #GMemChunk. Used in g_mem_chunk_new() and
1062 * g_mem_chunk_create() to specify that atoms will be freed
1063 * individually.
1065 #define G_ALLOC_AND_FREE 2
1066 #endif
1068 struct _GMemChunk {
1069 guint alloc_size; /* the size of an atom */
1073 * g_mem_chunk_new:
1074 * @name: a string to identify the #GMemChunk. It is not copied so it
1075 * should be valid for the lifetime of the #GMemChunk. It is
1076 * only used in g_mem_chunk_print(), which is used for debugging.
1077 * @atom_size: the size, in bytes, of each element in the #GMemChunk.
1078 * @area_size: the size, in bytes, of each block of memory allocated to
1079 * contain the atoms.
1080 * @type: the type of the #GMemChunk. #G_ALLOC_AND_FREE is used if the
1081 * atoms will be freed individually. #G_ALLOC_ONLY should be
1082 * used if atoms will never be freed individually.
1083 * #G_ALLOC_ONLY is quicker, since it does not need to track
1084 * free atoms, but it obviously wastes memory if you no longer
1085 * need many of the atoms.
1086 * @Returns: the new #GMemChunk.
1088 * Creates a new #GMemChunk.
1090 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1091 * allocator</link> instead
1093 GMemChunk*
1094 g_mem_chunk_new (const gchar *name,
1095 gint atom_size,
1096 gsize area_size,
1097 gint type)
1099 GMemChunk *mem_chunk;
1100 g_return_val_if_fail (atom_size > 0, NULL);
1102 mem_chunk = g_slice_new (GMemChunk);
1103 mem_chunk->alloc_size = atom_size;
1104 return mem_chunk;
1108 * g_mem_chunk_destroy:
1109 * @mem_chunk: a #GMemChunk.
1111 * Frees all of the memory allocated for a #GMemChunk.
1113 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1114 * allocator</link> instead
1116 void
1117 g_mem_chunk_destroy (GMemChunk *mem_chunk)
1119 g_return_if_fail (mem_chunk != NULL);
1121 g_slice_free (GMemChunk, mem_chunk);
1125 * g_mem_chunk_alloc:
1126 * @mem_chunk: a #GMemChunk.
1127 * @Returns: a pointer to the allocated atom.
1129 * Allocates an atom of memory from a #GMemChunk.
1131 * Deprecated:2.10: Use g_slice_alloc() instead
1133 gpointer
1134 g_mem_chunk_alloc (GMemChunk *mem_chunk)
1136 g_return_val_if_fail (mem_chunk != NULL, NULL);
1138 return g_slice_alloc (mem_chunk->alloc_size);
1142 * g_mem_chunk_alloc0:
1143 * @mem_chunk: a #GMemChunk.
1144 * @Returns: a pointer to the allocated atom.
1146 * Allocates an atom of memory from a #GMemChunk, setting the memory to
1147 * 0.
1149 * Deprecated:2.10: Use g_slice_alloc0() instead
1151 gpointer
1152 g_mem_chunk_alloc0 (GMemChunk *mem_chunk)
1154 g_return_val_if_fail (mem_chunk != NULL, NULL);
1156 return g_slice_alloc0 (mem_chunk->alloc_size);
1160 * g_mem_chunk_free:
1161 * @mem_chunk: a #GMemChunk.
1162 * @mem: a pointer to the atom to free.
1164 * Frees an atom in a #GMemChunk. This should only be called if the
1165 * #GMemChunk was created with #G_ALLOC_AND_FREE. Otherwise it will
1166 * simply return.
1168 * Deprecated:2.10: Use g_slice_free1() instead
1170 void
1171 g_mem_chunk_free (GMemChunk *mem_chunk,
1172 gpointer mem)
1174 g_return_if_fail (mem_chunk != NULL);
1176 g_slice_free1 (mem_chunk->alloc_size, mem);
1180 * g_mem_chunk_clean:
1181 * @mem_chunk: a #GMemChunk.
1183 * Frees any blocks in a #GMemChunk which are no longer being used.
1185 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1186 * allocator</link> instead
1188 void g_mem_chunk_clean (GMemChunk *mem_chunk) {}
1191 * g_mem_chunk_reset:
1192 * @mem_chunk: a #GMemChunk.
1194 * Resets a GMemChunk to its initial state. It frees all of the
1195 * currently allocated blocks of memory.
1197 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1198 * allocator</link> instead
1200 void g_mem_chunk_reset (GMemChunk *mem_chunk) {}
1204 * g_mem_chunk_print:
1205 * @mem_chunk: a #GMemChunk.
1207 * Outputs debugging information for a #GMemChunk. It outputs the name
1208 * of the #GMemChunk (set with g_mem_chunk_new()), the number of bytes
1209 * used, and the number of blocks of memory allocated.
1211 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1212 * allocator</link> instead
1214 void g_mem_chunk_print (GMemChunk *mem_chunk) {}
1218 * g_mem_chunk_info:
1220 * Outputs debugging information for all #GMemChunk objects currently
1221 * in use. It outputs the number of #GMemChunk objects currently
1222 * allocated, and calls g_mem_chunk_print() to output information on
1223 * each one.
1225 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1226 * allocator</link> instead
1228 void g_mem_chunk_info (void) {}
1231 * g_blow_chunks:
1233 * Calls g_mem_chunk_clean() on all #GMemChunk objects.
1235 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1236 * allocator</link> instead
1238 void g_blow_chunks (void) {}
1241 * g_chunk_new0:
1242 * @type: the type of the #GMemChunk atoms, typically a structure name.
1243 * @chunk: a #GMemChunk.
1244 * @Returns: a pointer to the allocated atom, cast to a pointer to
1245 * @type.
1247 * A convenience macro to allocate an atom of memory from a #GMemChunk.
1248 * It calls g_mem_chunk_alloc0() and casts the returned atom to a
1249 * pointer to the given type, avoiding a type cast in the source code.
1251 * Deprecated:2.10: Use g_slice_new0() instead
1255 * g_chunk_free:
1256 * @mem: a pointer to the atom to be freed.
1257 * @mem_chunk: a #GMemChunk.
1259 * A convenience macro to free an atom of memory from a #GMemChunk. It
1260 * simply switches the arguments and calls g_mem_chunk_free() It is
1261 * included simply to complement the other convenience macros,
1262 * g_chunk_new() and g_chunk_new0().
1264 * Deprecated:2.10: Use g_slice_free() instead
1268 * g_chunk_new:
1269 * @type: the type of the #GMemChunk atoms, typically a structure name.
1270 * @chunk: a #GMemChunk.
1271 * @Returns: a pointer to the allocated atom, cast to a pointer to
1272 * @type.
1274 * A convenience macro to allocate an atom of memory from a #GMemChunk.
1275 * It calls g_mem_chunk_alloc() and casts the returned atom to a
1276 * pointer to the given type, avoiding a type cast in the source code.
1278 * Deprecated:2.10: Use g_slice_new() instead
1282 * g_mem_chunk_create:
1283 * @type: the type of the atoms, typically a structure name.
1284 * @pre_alloc: the number of atoms to store in each block of memory.
1285 * @alloc_type: the type of the #GMemChunk. #G_ALLOC_AND_FREE is used
1286 * if the atoms will be freed individually. #G_ALLOC_ONLY
1287 * should be used if atoms will never be freed
1288 * individually. #G_ALLOC_ONLY is quicker, since it does
1289 * not need to track free atoms, but it obviously wastes
1290 * memory if you no longer need many of the atoms.
1291 * @Returns: the new #GMemChunk.
1293 * A convenience macro for creating a new #GMemChunk. It calls
1294 * g_mem_chunk_new(), using the given type to create the #GMemChunk
1295 * name. The atom size is determined using
1296 * <function>sizeof()</function>, and the area size is calculated by
1297 * multiplying the @pre_alloc parameter with the atom size.
1299 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1300 * allocator</link> instead
1305 * g_allocator_new:
1306 * @name: the name of the #GAllocator. This name is used to set the
1307 * name of the #GMemChunk used by the #GAllocator, and is only
1308 * used for debugging.
1309 * @n_preallocs: the number of elements in each block of memory
1310 * allocated. Larger blocks mean less calls to
1311 * g_malloc(), but some memory may be wasted. (GLib uses
1312 * 128 elements per block by default.) The value must be
1313 * between 1 and 65535.
1314 * @Returns: a new #GAllocator.
1316 * Creates a new #GAllocator.
1318 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1319 * allocator</link> instead
1321 GAllocator*
1322 g_allocator_new (const gchar *name,
1323 guint n_preallocs)
1325 static struct _GAllocator {
1326 gchar *name;
1327 guint16 n_preallocs;
1328 guint is_unused : 1;
1329 guint type : 4;
1330 GAllocator *last;
1331 GMemChunk *mem_chunk;
1332 gpointer free_list;
1333 } dummy = {
1334 "GAllocator is deprecated", 1, TRUE, 0, NULL, NULL, NULL,
1336 /* some (broken) GAllocator uses depend on non-NULL allocators */
1337 return (void*) &dummy;
1341 * g_allocator_free:
1342 * @allocator: a #GAllocator.
1344 * Frees all of the memory allocated by the #GAllocator.
1346 * Deprecated:2.10: Use the <link linkend="glib-Memory-Slices">slice
1347 * allocator</link> instead
1349 void
1350 g_allocator_free (GAllocator *allocator)
1354 #ifdef ENABLE_GC_FRIENDLY_DEFAULT
1355 gboolean g_mem_gc_friendly = TRUE;
1356 #else
1358 * g_mem_gc_friendly:
1360 * This variable is %TRUE if the <envar>G_DEBUG</envar> environment variable
1361 * includes the key <link linkend="G_DEBUG">gc-friendly</link>.
1363 gboolean g_mem_gc_friendly = FALSE;
1364 #endif
1366 static void
1367 g_mem_init_nomessage (void)
1369 gchar buffer[1024];
1370 const gchar *val;
1371 const GDebugKey keys[] = {
1372 { "gc-friendly", 1 },
1374 gint flags;
1375 if (g_mem_initialized)
1376 return;
1377 /* don't use g_malloc/g_message here */
1378 val = _g_getenv_nomalloc ("G_DEBUG", buffer);
1379 flags = !val ? 0 : g_parse_debug_string (val, keys, G_N_ELEMENTS (keys));
1380 if (flags & 1) /* gc-friendly */
1382 g_mem_gc_friendly = TRUE;
1384 g_mem_initialized = TRUE;
1387 void
1388 _g_mem_thread_init_noprivate_nomessage (void)
1390 /* we may only create mutexes here, locking/
1391 * unlocking a mutex does not yet work.
1393 g_mem_init_nomessage();
1394 #ifndef G_DISABLE_CHECKS
1395 gmem_profile_mutex = g_mutex_new ();
1396 #endif