Skip to content

What is the behavior of malloc with size zero? #1277

Open

Description

@gnzlbg

The docs of mallocx state:

Behavior is undefined if size is 0.

but the docs for malloc do not state anything about its behavior if the size is 0.

I suppose that it follows the C11 standard, that is, from 7.20.3.1:

If the size of the space requested is zero, the behavior is implementation defined:
either a null pointer is returned, or the behavior is as if the size were some
nonzero value, except that the returned pointer shall not be used to access an object.

Since jemalloc is the implementation, it should defined the behavior, either to one of the two behaviors allowed, or to both (that is, stating that any of both allowed behaviors could happen).

Activity

  1. gnzlbg commented on Jul 12, 2018

    @gnzlbg
    ContributorAuthor

    Note: the docs of free say:

    The free() function causes the allocated memory referenced by ptr to be made available for future allocations. If ptr is NULL, no action occurs.

    so this might indicate that malloc behavior when size is 0 is to return NULL.

  2. rustyx commented on Sep 1, 2018

    @rustyx
    Contributor

    je_malloc(0) essentially behaves the same as je_malloc(1):

    	if (sopts->bump_empty_alloc) {
    		if (unlikely(size == 0)) {
    			size = 1;
    		}
    	}
    

    So it is conforming.

    Though spelling out this exact behavior in the manual will lead to people relying on it when they shouldn't.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions