Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

Can malloc Return NULL? What C and POSIX Require

For nonzero requests, malloc can return NULL when allocation fails. Check the pointer first; errno and zero-size behavior depend on the C or POSIX contract, while Linux overcommit adds a separate risk.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Yes. For a request larger than zero, malloc can return a null pointer when it cannot allocate the requested space. Always check the returned pointer before using it. POSIX also requires errno to be set on failure; portable ISO C does not. Linux adds an important caveat: a successful allocation does not guarantee the memory will remain available when your program later accesses it.

What does a NULL return mean?

For a nonzero request, a null return means the allocator could not provide the requested space. POSIX states, “If the space cannot be allocated, a null pointer shall be returned.” The POSIX Programmer’s Manual for malloc specifies that failure returns a null pointer and sets errno; ENOMEM indicates insufficient storage.

The return value is the reliable test in C: if it is null, do not dereference it. A null result is not necessarily proof that the machine has run out of physical RAM. On Linux, documented causes also include process address-space or data limits and the system mapping-count limit.

Should you check whether malloc returned NULL?

Yes. Save the result, test it, and only use the pointer after the check succeeds. The GNU C Library’s allocation guidance likewise demonstrates checking for a null pointer and taking an explicit failure path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#include <stdint.h>
#include <stdlib.h>

int *items = malloc(count * sizeof *items);
if (items == NULL) {
    /* Report failure, unwind, reduce work, or exit as appropriate. */
    return ERROR_CODE;
}

This example assumes that the size calculation is valid. Check separately that count * sizeof *items cannot overflow; otherwise the program may request less memory than intended. What to do after failure depends on what the program can safely undo. It might report an error, release resources already acquired, reduce the work, or terminate rather than continue in an invalid state.

Does malloc set errno?

It depends on the contract your program targets. POSIX requires errno to be set when allocation fails, with ENOMEM identifying insufficient storage. ISO C does not provide a portable guarantee that errno is set by malloc. As the Linux malloc(3) manual explains, POSIX requires this behavior while the C standard does not.

Check the pointer first. If you are writing for POSIX and need a diagnostic, you can inspect errno after a failed nonzero request. For code intended to be portable across C implementations, do not use errno as the failure test.

Does malloc(0) return NULL?

It may, but zero-size allocation is a special case and should not be confused with failure for an ordinary request. POSIX permits malloc(0) to return either a null pointer or a pointer to a zero-size allocation. A non-null result must not be used to access an object. The POSIX specification also allows an implementation-defined errno value in the null-return case.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If an empty collection needs no storage, handle that case explicitly—for example, skip the allocation or use a separate representation for the empty collection—instead of relying on how a particular implementation handles malloc(0).

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why can Linux allocation succeed and still lead to a memory problem?

Linux documents that, by default, it follows an optimistic memory-allocation strategy. A non-null return therefore does not guarantee that memory will be available when the program later touches it. If the system subsequently runs out of memory, the OOM killer may terminate one or more processes. This is Linux system behavior layered on top of the allocation API; it does not change the null-return rule for an allocation failure.

Linux also lists limits that can cause ENOMEM even when “the computer ran out of RAM” is not an adequate explanation. These include reaching RLIMIT_AS or RLIMIT_DATA, or exceeding /proc/sys/vm/max_map_count. The details are described in the Linux malloc(3) manual.

Best Value

How the rules differ by environment

Environment Meaning of NULL for a nonzero request Is errno required? Key qualification
ISO C portability The requested allocation was not provided. No portable guarantee. malloc(0) has separate implementation-defined behavior, as summarized by cppreference.
POSIX Allocation failure returns null. Yes; ENOMEM indicates insufficient storage. Zero-size requests have separate rules in the POSIX specification.
Linux, default allocation policy The API still returns null when the allocator reports failure. The Linux manual documents errno on error. A non-null result does not guarantee future availability when memory is accessed; the OOM killer may act, as described in the Linux manual.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.