malloc man page

malloc, free, calloc, realloc — allocate and free dynamic memory


#include <stdlib.h>

void *malloc(size_t size);
void free(void *ptr);
void *calloc(size_t nmemb, size_t size);
void *realloc(void *ptr, size_t size);
void *reallocarray(void *ptr, size_t nmemb, size_t size);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):




The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.

The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. If nmemb or size is 0, then calloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc(), or realloc(). If the area pointed to was moved, a free(ptr) is done.

The reallocarray() function changes the size of the memory block pointed to by ptr to be large enough for an array of nmemb elements, each of which is size bytes. It is equivalent to the call

   realloc(ptr, nmemb * size);

However, unlike that realloc() call, reallocarray() fails safely in the case where the multiplication would overflow. If such an overflow occurs, reallocarray() returns NULL, sets errno to ENOMEM, and leaves the original block of memory unchanged.

Return Value

The malloc() and calloc() functions return a pointer to the allocated memory, which is suitably aligned for any built-in type. On error, these functions return NULL. NULL may also be returned by a successful call to malloc() with a size of zero, or by a successful call to calloc() with nmemb or size equal to zero.

The free() function returns no value.

The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any built-in type and may be different from ptr, or NULL if the request fails. If size was equal to 0, either NULL or a pointer suitable to be passed to free() is returned. If realloc() fails, the original block is left untouched; it is not freed or moved.

On success, the reallocarray() function returns a pointer to the newly allocated memory. On failure, it returns NULL and the original block of memory is left untouched.


calloc(), malloc(), realloc(), and reallocarray() can fail with the following error:


Out of memory. Possibly, the application hit the RLIMIT_AS or RLIMIT_DATA limit described in getrlimit(2).


For an explanation of the terms used in this section, see attributes(7).

Interface Attribute Value
malloc(), free(),
calloc(), realloc()
Thread safety MT-Safe

Conforming to

malloc(), free(), calloc(), realloc(): POSIX.1-2001, POSIX.1-2008, C89, C99.

reallocarray() is a nonstandard extension that first appeared in OpenBSD 5.6 and FreeBSD 11.0.


By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. In case it turns out that the system is out of memory, one or more processes will be killed by the OOM killer. For more information, see the description of /proc/sys/vm/overcommit_memory and /proc/sys/vm/oom_adj in proc(5), and the Linux kernel source file Documentation/vm/overcommit-accounting.

Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2). When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2). MMAP_THRESHOLD is 128 kB by default, but is adjustable using mallopt(3). Prior to Linux 4.7 allocations performed using mmap(2) were unaffected by the RLIMIT_DATA resource limit; since Linux 4.7, this limit is also enforced for allocations performed using mmap(2).

To avoid corruption in multithreaded applications, mutexes are used internally to protect the memory-management data structures employed by these functions. In a multithreaded application in which threads simultaneously allocate and free memory, there could be contention for these mutexes. To scalably handle memory allocation in multithreaded applications, glibc creates additional memory allocation arenas if mutex contention is detected. Each arena is a large region of memory that is internally allocated by the system (using brk(2) or mmap(2)), and managed with its own mutexes.

SUSv2 requires malloc(), calloc(), and realloc() to set errno to ENOMEM upon failure. Glibc assumes that this is done (and the glibc versions of these routines do this); if you use a private malloc implementation that does not set errno, then certain library routines may fail without having a reason in errno.

Crashes in malloc(), calloc(), realloc(), or free() are almost always related to heap corruption, such as overflowing an allocated chunk or freeing the same pointer twice.

The malloc() implementation is tunable via environment variables; see mallopt(3) for details.

See Also

brk(2), mmap(2), alloca(3), malloc_get_state(3), malloc_info(3), malloc_trim(3), malloc_usable_size(3), mallopt(3), mcheck(3), mtrace(3), posix_memalign(3)


This page is part of release 4.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at

Referenced By

alloca(3), archive_entry_linkify(3), ares_library_init(3), argz_add(3), ason_inspect(3), ason_iterators(3), asprintf(3), asr_run(3), atf-c-api(3), ausearch_add_expression(3), avc_init(3), backtrace(3), basename(3), bitstring(3), brk(2), canonicalize_file_name(3), cdt(3), cfree(3), confuse.h(3), CPU_SET(3), ecalloc(3), efence(3), end(3), environ(7), exec(3), explain(1), explain(3), explain_calloc(3), explain_calloc_or_die(3), explain_malloc(3), explain_malloc_or_die(3), explain_output(3), explain_realloc(3), explain_realloc_or_die(3), FcStrFree(3), fgetln(3), fgetwln(3), fio(1), fmemcmp(3), fmemcmpi(3), fopen(3), fseek(3), fstrcasecmp(3), fstrcasecmpi(3), fstrcmp(3), fstrcmpi(3), fstrcoll(3), fstrcolli(3), fts(3), ftw(3), funopen.3bsd(3), fwcscmp(3), fwcscmpi(3), gc(3), gd_alloc_funcs(3), gdbm(3), gd_error(3), gd_fragment_affixes(3), gd_free_entry_strings(3), gd_linterp_tablename(3), gd_open(3), gd_raw_filename(3), gearman_allocator_t(3), gearman_client_context(3), gearman_client_do_job_handle(3), gearman_client_do_status(3), gearman_client_set_memory_allocators(3), gearman_client_set_task_context_free_fn(3), gearman_client_set_timeout(3), gearman_client_set_workload_fn(3), gearman_client_set_workload_free_fn(3), gearman_client_set_workload_malloc_fn(3), gearman_client_st(3), gearman_client_task_free_all(3), gearman_client_timeout(3), gearman_job_free(3), gearman_job_free_all(3), gearman_job_function_name(3), gearman_job_handle(3), gearman_job_send_complete(3), gearman_job_send_data(3), gearman_job_send_exception(3), gearman_job_send_fail(3), gearman_job_send_status(3), gearman_job_send_warning(3), gearman_job_st(3), gearman_job_take_workload(3), gearman_job_unique(3), gearman_job_use_client(3), gearman_job_workload(3), gearman_job_workload_size(3), gearman_task_context(3), gearman_task_data(3), gearman_task_data_size(3), gearman_task_denominator(3), gearman_task_error(3), gearman_task_free(3), gearman_task_function_name(3), gearman_task_give_workload(3), gearman_task_is_known(3), gearman_task_is_running(3), gearman_task_job_handle(3), gearman_task_numerator(3), gearman_task_recv_data(3), gearman_task_return(3), gearman_task_send_workload(3), gearman_task_set_context(3), gearman_task_st(3), gearman_task_take_data(3), gearman_task_unique(3), gearman_worker_add_function(3), gearman_worker_context(3), gearman_worker_function_exist(3), gearman_worker_grab_job(3), gearman_worker_register(3), gearman_worker_set_context(3), gearman_worker_set_memory_allocators(3), gearman_worker_set_timeout(3), gearman_worker_set_workload_free_fn(3), gearman_worker_set_workload_malloc_fn(3), gearman_worker_st(3), gearman_worker_timeout(3), gearman_worker_unregister(3), gearman_worker_unregister_all(3), gearman_worker_wait(3), gearman_worker_work(3), genders_index_attrvals(3), genders_load_data(3), genders_nodelist_create(3), genders_query(3), genders_testquery(3), getcwd(3), getgrent(3), getgrnam(3), getifaddrs(3), getline(3), getpwent(3), getpwnam(3), getrlimit(2), gl_getcontext(3), glob(3), guestfs(3), guestfs-hacking(1), guestfs-java(3), hbwmalloc(3), hsearch(3), idn2_free(3), if_nameindex(3), krb5_encrypt(3), krb5_get_default_principal(3), krb5_get_default_realm(3), krb5_support(3), lber-memory(3), ldap_memfree(3), ldap_perror(3), libinnhist(3), libpmemobj(3), libssh2_userauth_keyboard_interactive_ex(3), libvmem(3), libvmmalloc(3), lwres_context(3), mallinfo(3), malloc_get_state(3), malloc_hook(3), malloc_info(3), malloc_stats(3), malloc_trim(3), malloc_usable_size(3), mallopt(3), mandoc(3), mandocd(8), mandoc_malloc(3), mcheck(3), md5.3bsd(3), memcached_fetch_execute(3), memcached_fetch_result(3), memcached_get(3), memcached_get_by_key(3), memcached_mget(3), memcached_mget_by_key(3), memcached_mget_execute(3), memcached_mget_execute_by_key(3), memkind(3), memtester(8), memusage(1), mhash(3), mlock(2), mm(3), mremap(2), mtrace(3), nodeupdown_get_up_nodes_list(3), nodeupdown_get_up_nodes_string(3), nodeupdown_is_node_up(3), nodeupdown_load_data(3), nodeupdown_nodelist_create(3), numa(3), open_memstream(3), ossp-uuid(3), owcapi(1), ownet(1), pam_conv(3), perldebguts(1), perlipc(1), __pmAFblock(3), PMAPI(3), pmCreateFetchGroup(3), pmdaChildren(3), pmdaFetch(3), pmdaInstance(3), pmdaText(3), pmdatrace(3), pmDiscoverServices(3), pmExtractValue(3), pmFetch(3), pmFetchArchive(3), __pmFreeAttrsSpec(3), __pmFreeHostSpec(3), pmFreeMetricSpec(3), __pmFreeProfile(3), pmFreeResult(3), pmGetChildren(3), pmGetChildrenStatus(3), pmGetInDom(3), pmGetInDomArchive(3), pmLookupInDomText(3), pmLookupText(3), pmNameAll(3), pmNameID(3), pmNameInDom(3), pmNameInDomArchive(3), pmNewContextZone(3), pmNewZone(3), __pmParseCtime(3), pmParseInterval(3), __pmParseTime(3), pmRegisterDerived(3), posix_memalign(3), proc(5), pthread_setcancelstate(3), pthsem(3), radixsort(3), random_r(3), readdir(3), readline(3), readpass(3), reallocarray(3), reallocf(3), realpath(3), ruby(1), samefile(1), scandir(3), scanf(3), sd_bus_creds_get_pid(3), sd_bus_error(3), sd_bus_path_encode(3), sd_get_seats(3), sd_journal_get_catalog(3), sd_journal_get_cursor(3), sd-login(3), sd_machine_get_class(3), sd_pid_get_session(3), sd_seat_get_active(3), sd_session_is_active(3), sd_uid_get_state(3), seccomp_syscall_resolve_name(3), security_class_to_string(3), selinux_boolean_sub(3), selinux_getpolicytype(3), selinux_raw_context_to_color(3), setbuf(3), setmode(3), signal-safety(7), slurm_checkpoint_error(3), strdup(3), stress-ng(1), string(3), stringlist(3), talloc(3), tar_open(3), tcsh(1), tempnam(3), termkey_new(3), TIFFmemory.3tiff(3), tst(3), upscli_splitaddr(3), upscli_splitname(3), vsp(3), waffle_config(3), waffle_context(3), waffle_display(3), waffle_window(3), wcsdup(3), wnsearch(3), zip_file_extra_field_get(3), zip_file_get_comment(3), zip_get_archive_comment(3), zzip_disk_mmap(3).

The man pages calloc(3), free(3) and realloc(3) are aliases of malloc(3).

2017-09-15 GNU Linux Programmer's Manual