malloc() and free()

What is malloc()

In malloc.c line 597, we find an explanation of malloc():

/*
  malloc(size_t n)
  Returns a pointer to a newly allocated chunk of at least n bytes, or null
  if no space is available. Additionally, on failure, errno is
  set to ENOMEM on ANSI C systems.

  If n is zero, malloc returns a minimum-sized chunk. (The minimum
  size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit
  systems.)  On most systems, size_t is an unsigned type, so calls
  with negative arguments are interpreted as requests for huge amounts
  of space, which will often fail. The maximum supported value of n
  differs across systems, but is in all cases less than the maximum
  representable value of a size_t.
*/

Key ideas:

  • If n is zero, malloc returns a minimum-sized chunk (16 bytes for 32-bit machine and 32 bytes for 64-bits machine).

  • size_t is an unsigned type, so n < 0 => request huge amounts of space.

In malloc.c line 3285, we find the implementation of malloc():

What is free()

In malloc.c line 614, we find an explanation of free():

Key ideas:

  • If p = NULL then free(p) has no effect.

  • Double free is dangerous.

In malloc.c line 3350, we find the implementation of free():

Last updated

Was this helpful?