1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * SPDX-License-Identifier: LGPL-2.1-or-later
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
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/.
35 #if defined(HAVE_POSIX_MEMALIGN) && !defined(_XOPEN_SOURCE)
36 # define _XOPEN_SOURCE 600
39 #if defined(HAVE_MEMALIGN) || defined(HAVE__ALIGNED_MALLOC)
40 /* Required for _aligned_malloc() and _aligned_free() on Windows */
44 #ifdef HAVE__ALIGNED_MALLOC
45 /* _aligned_malloc() takes parameters of aligned_malloc() in reverse order */
46 # define aligned_alloc(alignment, size) _aligned_malloc (size, alignment)
48 /* _aligned_malloc()'ed memory must be freed by _align_free() on MSVC */
49 # define aligned_free(x) _aligned_free (x)
51 # define aligned_free(x) free (x)
59 #include "gbacktrace.h"
60 #include "gtestutils.h"
62 #include "glib_trace.h"
65 * having G_DISABLE_CHECKS defined disables use of glib_mem_profiler_table and
67 * If g_mem_gc_friendly is TRUE, freed memory should be 0-wiped.
70 /* --- variables --- */
71 static GMemVTable glib_mem_vtable = {
82 * @Short_Description: general memory-handling
83 * @Title: Memory Allocation
85 * These functions provide support for allocating and freeing memory.
87 * If any call to allocate memory using functions g_new(), g_new0(), g_renew(),
88 * g_malloc(), g_malloc0(), g_malloc0_n(), g_realloc(), and g_realloc_n()
89 * fails, the application is terminated. This also means that there is no
90 * need to check if the call succeeded. On the other hand, the `g_try_...()` family
91 * of functions returns %NULL on failure that can be used as a check
92 * for unsuccessful memory allocation. The application is not terminated
95 * As all GLib functions and data structures use `g_malloc()` internally, unless
96 * otherwise specified, any allocation failure will result in the application
99 * It's important to match g_malloc() (and wrappers such as g_new()) with
100 * g_free(), g_slice_alloc() (and wrappers such as g_slice_new()) with
101 * g_slice_free(), plain malloc() with free(), and (if you're using C++)
102 * new with delete and new[] with delete[]. Otherwise bad things can happen,
103 * since these allocators may use different memory pools (and new/delete call
104 * constructors and destructors).
106 * Since GLib 2.46 g_malloc() is hardcoded to always use the system malloc
110 /* --- functions --- */
113 * @n_bytes: the number of bytes to allocate
115 * Allocates @n_bytes bytes of memory.
116 * If @n_bytes is 0 it returns %NULL.
118 * If the allocation fails (because the system is out of memory),
119 * the program is terminated.
121 * Returns: a pointer to the allocated memory
124 g_malloc (gsize n_bytes)
126 if (G_LIKELY (n_bytes))
130 mem = malloc (n_bytes);
131 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 0));
135 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
139 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 0, 0));
146 * @n_bytes: the number of bytes to allocate
148 * Allocates @n_bytes bytes of memory, initialized to 0's.
149 * If @n_bytes is 0 it returns %NULL.
151 * If the allocation fails (because the system is out of memory),
152 * the program is terminated.
154 * Returns: a pointer to the allocated memory
157 g_malloc0 (gsize n_bytes)
159 if (G_LIKELY (n_bytes))
163 mem = calloc (1, n_bytes);
164 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 1, 0));
168 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
172 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) n_bytes, 1, 0));
179 * @mem: (nullable): the memory to reallocate
180 * @n_bytes: new size of the memory in bytes
182 * Reallocates the memory pointed to by @mem, so that it now has space for
183 * @n_bytes bytes of memory. It returns the new address of the memory, which may
184 * have been moved. @mem may be %NULL, in which case it's considered to
185 * have zero-length. @n_bytes may be 0, in which case %NULL will be returned
186 * and @mem will be freed unless it is %NULL.
188 * If the allocation fails (because the system is out of memory),
189 * the program is terminated.
191 * Returns: the new address of the allocated memory
194 g_realloc (gpointer mem,
199 if (G_LIKELY (n_bytes))
201 newmem = realloc (mem, n_bytes);
202 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 0));
206 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
212 TRACE (GLIB_MEM_REALLOC((void*) NULL, (void*)mem, 0, 0));
219 * @mem: (nullable): the memory to free
221 * Frees the memory pointed to by @mem.
223 * If @mem is %NULL it simply returns, so there is no need to check @mem
224 * against %NULL before calling this function.
227 g_free (gpointer mem)
230 TRACE(GLIB_MEM_FREE((void*) mem));
234 * g_clear_pointer: (skip)
235 * @pp: (not nullable): a pointer to a variable, struct member etc. holding a
237 * @destroy: a function to which a gpointer can be passed, to destroy *@pp
239 * Clears a reference to a variable.
241 * @pp must not be %NULL.
243 * If the reference is %NULL then this function does nothing.
244 * Otherwise, the variable is destroyed using @destroy and the
245 * pointer is set to %NULL.
247 * A macro is also included that allows this function to be used without
248 * pointer casts. This will mask any warnings about incompatible function types
249 * or calling conventions, so you must ensure that your @destroy function is
250 * compatible with being called as `GDestroyNotify` using the standard calling
251 * convention for the platform that GLib was compiled for; otherwise the program
252 * will experience undefined behaviour.
256 #undef g_clear_pointer
258 g_clear_pointer (gpointer *pp,
259 GDestroyNotify destroy)
273 * @n_bytes: number of bytes to allocate.
275 * Attempts to allocate @n_bytes, and returns %NULL on failure.
276 * Contrast with g_malloc(), which aborts the program on failure.
278 * Returns: the allocated memory, or %NULL.
281 g_try_malloc (gsize n_bytes)
285 if (G_LIKELY (n_bytes))
286 mem = malloc (n_bytes);
290 TRACE (GLIB_MEM_ALLOC((void*) mem, (unsigned int) n_bytes, 0, 1));
297 * @n_bytes: number of bytes to allocate
299 * Attempts to allocate @n_bytes, initialized to 0's, and returns %NULL on
300 * failure. Contrast with g_malloc0(), which aborts the program on failure.
303 * Returns: the allocated memory, or %NULL
306 g_try_malloc0 (gsize n_bytes)
310 if (G_LIKELY (n_bytes))
311 mem = calloc (1, n_bytes);
320 * @mem: (nullable): previously-allocated memory, or %NULL.
321 * @n_bytes: number of bytes to allocate.
323 * Attempts to realloc @mem to a new size, @n_bytes, and returns %NULL
324 * on failure. Contrast with g_realloc(), which aborts the program
327 * If @mem is %NULL, behaves the same as g_try_malloc().
329 * Returns: the allocated memory, or %NULL.
332 g_try_realloc (gpointer mem,
337 if (G_LIKELY (n_bytes))
338 newmem = realloc (mem, n_bytes);
345 TRACE (GLIB_MEM_REALLOC((void*) newmem, (void*)mem, (unsigned int) n_bytes, 1));
351 #define SIZE_OVERFLOWS(a,b) (G_UNLIKELY ((b) > 0 && (a) > G_MAXSIZE / (b)))
355 * @n_blocks: the number of blocks to allocate
356 * @n_block_bytes: the size of each block in bytes
358 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
359 * but care is taken to detect possible overflow during multiplication.
361 * If the allocation fails (because the system is out of memory),
362 * the program is terminated.
365 * Returns: a pointer to the allocated memory
368 g_malloc_n (gsize n_blocks,
371 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
373 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
374 G_STRLOC, n_blocks, n_block_bytes);
377 return g_malloc (n_blocks * n_block_bytes);
382 * @n_blocks: the number of blocks to allocate
383 * @n_block_bytes: the size of each block in bytes
385 * This function is similar to g_malloc0(), allocating (@n_blocks * @n_block_bytes) bytes,
386 * but care is taken to detect possible overflow during multiplication.
388 * If the allocation fails (because the system is out of memory),
389 * the program is terminated.
392 * Returns: a pointer to the allocated memory
395 g_malloc0_n (gsize n_blocks,
398 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
400 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
401 G_STRLOC, n_blocks, n_block_bytes);
404 return g_malloc0 (n_blocks * n_block_bytes);
409 * @mem: (nullable): the memory to reallocate
410 * @n_blocks: the number of blocks to allocate
411 * @n_block_bytes: the size of each block in bytes
413 * This function is similar to g_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
414 * but care is taken to detect possible overflow during multiplication.
416 * If the allocation fails (because the system is out of memory),
417 * the program is terminated.
420 * Returns: the new address of the allocated memory
423 g_realloc_n (gpointer mem,
427 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
429 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
430 G_STRLOC, n_blocks, n_block_bytes);
433 return g_realloc (mem, n_blocks * n_block_bytes);
438 * @n_blocks: the number of blocks to allocate
439 * @n_block_bytes: the size of each block in bytes
441 * This function is similar to g_try_malloc(), allocating (@n_blocks * @n_block_bytes) bytes,
442 * but care is taken to detect possible overflow during multiplication.
445 * Returns: the allocated memory, or %NULL.
448 g_try_malloc_n (gsize n_blocks,
451 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
454 return g_try_malloc (n_blocks * n_block_bytes);
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_malloc0(), 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_malloc0_n (gsize n_blocks,
472 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
475 return g_try_malloc0 (n_blocks * n_block_bytes);
480 * @mem: (nullable): previously-allocated memory, or %NULL.
481 * @n_blocks: the number of blocks to allocate
482 * @n_block_bytes: the size of each block in bytes
484 * This function is similar to g_try_realloc(), allocating (@n_blocks * @n_block_bytes) bytes,
485 * but care is taken to detect possible overflow during multiplication.
488 * Returns: the allocated memory, or %NULL.
491 g_try_realloc_n (gpointer mem,
495 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
498 return g_try_realloc (mem, n_blocks * n_block_bytes);
502 * g_mem_is_system_malloc:
504 * Checks whether the allocator used by g_malloc() is the system's
505 * malloc implementation. If it returns %TRUE memory allocated with
506 * malloc() can be used interchangeably with memory allocated using g_malloc().
507 * This function is useful for avoiding an extra copy of allocated memory returned
508 * by a non-GLib-based API.
510 * Returns: if %TRUE, malloc() and g_malloc() can be mixed.
512 * Deprecated: 2.46: GLib always uses the system malloc, so this function always
516 g_mem_is_system_malloc (void)
523 * @vtable: table of memory allocation routines.
525 * This function used to let you override the memory allocation function.
526 * However, its use was incompatible with the use of global constructors
527 * in GLib and GIO, because those use the GLib allocators before main is
528 * reached. Therefore this function is now deprecated and is just a stub.
530 * Deprecated: 2.46: This function now does nothing. Use other memory
531 * profiling tools instead
534 g_mem_set_vtable (GMemVTable *vtable)
536 g_warning (G_STRLOC ": custom memory allocation vtable not supported");
541 * glib_mem_profiler_table:
543 * Used to be a #GMemVTable containing profiling variants of the memory
544 * allocation functions, but this variable shouldn't be modified anymore.
546 * Deprecated: 2.46: Use other memory profiling tools instead
548 GMemVTable *glib_mem_profiler_table = &glib_mem_vtable;
553 * GLib used to support some tools for memory profiling, but this
554 * no longer works. There are many other useful tools for memory
555 * profiling these days which can be used instead.
557 * Deprecated: 2.46: Use other memory profiling tools instead
562 g_warning (G_STRLOC ": memory profiling not supported");
567 * @n_blocks: the number of blocks to allocate
568 * @n_block_bytes: the size of each block in bytes
569 * @alignment: the alignment to be enforced, which must be a positive power of 2
570 * and a multiple of `sizeof(void*)`
572 * This function is similar to g_malloc(), allocating (@n_blocks * @n_block_bytes)
573 * bytes, but care is taken to align the allocated memory to with the given
574 * alignment value. Additionally, it will detect possible overflow during
577 * If the allocation fails (because the system is out of memory),
578 * the program is terminated.
580 * Aligned memory allocations returned by this function can only be
581 * freed using g_aligned_free().
583 * Returns: (transfer full): the allocated memory
588 g_aligned_alloc (gsize n_blocks,
595 if (G_UNLIKELY ((alignment == 0) || (alignment & (alignment - 1)) != 0))
597 g_error ("%s: alignment %"G_GSIZE_FORMAT" must be a positive power of two",
598 G_STRLOC, alignment);
601 if (G_UNLIKELY ((alignment % sizeof (void *)) != 0))
603 g_error ("%s: alignment %"G_GSIZE_FORMAT" must be a multiple of %"G_GSIZE_FORMAT,
604 G_STRLOC, alignment, sizeof (void *));
607 if (SIZE_OVERFLOWS (n_blocks, n_block_bytes))
609 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"*%"G_GSIZE_FORMAT" bytes",
610 G_STRLOC, n_blocks, n_block_bytes);
613 real_size = n_blocks * n_block_bytes;
615 if (G_UNLIKELY (real_size == 0))
617 TRACE(GLIB_MEM_ALLOC((void*) NULL, (int) real_size, 0, 0));
621 /* We need to clear errno because posix_memalign() will use its return
622 * value in the same way memalign() and aligned_alloc() will set errno.
623 * Additionally, posix_memalign() will warn if its return value is left
626 * We handle all possible return values (ENOMEM and EINVAL) with either
627 * precondition or postcondition checking.
631 #if defined(HAVE_POSIX_MEMALIGN)
632 errno = posix_memalign (&res, alignment, real_size);
633 #elif defined(HAVE_ALIGNED_ALLOC) || defined(HAVE__ALIGNED_MALLOC)
634 /* real_size must be a multiple of alignment */
635 if (real_size % alignment != 0)
637 gsize offset = real_size % alignment;
639 if (G_MAXSIZE - real_size < (alignment - offset))
641 g_error ("%s: overflow allocating %"G_GSIZE_FORMAT"+%"G_GSIZE_FORMAT" bytes",
642 G_STRLOC, real_size, (alignment - offset));
645 real_size += (alignment - offset);
648 res = aligned_alloc (alignment, real_size);
649 #elif defined(HAVE_MEMALIGN)
650 res = memalign (alignment, real_size);
652 # error "This platform does not have an aligned memory allocator."
655 TRACE (GLIB_MEM_ALLOC((void*) res, (unsigned int) real_size, 0, 0));
659 g_error ("%s: failed to allocate %"G_GSIZE_FORMAT" bytes",
660 G_STRLOC, real_size);
667 * @n_blocks: the number of blocks to allocate
668 * @n_block_bytes: the size of each block in bytes
669 * @alignment: the alignment to be enforced, which must be a positive power of 2
670 * and a multiple of `sizeof(void*)`
672 * This function is similar to g_aligned_alloc(), but it will
673 * also clear the allocated memory before returning it.
675 * Returns: (transfer full): the allocated, cleared memory
680 g_aligned_alloc0 (gsize n_blocks,
684 gpointer res = g_aligned_alloc (n_blocks, n_block_bytes, alignment);
686 if (G_LIKELY (res != NULL))
687 memset (res, 0, n_blocks * n_block_bytes);
694 * @mem: (nullable): the memory to deallocate
696 * Frees the memory allocated by g_aligned_alloc().
701 g_aligned_free (gpointer mem)