Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The malloc() function, as well as the other memory allocation functions, returns either a null pointer or a pointer to the allocated space. Always test the returned pointer to ensure it is not NULL null before referencing the pointer. Handle the error condition appropriately when the returned pointer is NULLnull. When recovery from the allocation failure is not possible, propagate the failure to the caller.

...

When using realloc(), it is important to account for zero0-byte allocations. (See MEM04-C. Do not perform zero-length allocations.)

...

In addition to the C standard library functions abovementioned earlier, the following is an incomplete list of functions defined in POSIX that require error checking (list is incomplete).

Function

Successful Return

Error Return

errno

fmemopen()

pointer Pointer to a FILE object

NULL

ENOMEM

open_memstream()

pointer Pointer to a FILE object

NULL

ENOMEM

posix_memalign()

0

Nonzero #2 2unchanged #2

Unchanged 2

  1. Anchor
    1
    1
     Setting errno is a POSIX [ISO/IEC 9945:2008] extension to the C Standard.
  2. Anchor
    2
    2
     On error, posix_memalign() returns a value that corresponds to one of the constants defined in the <errno.h> header. The function does not set errno. The posix_memalign() function is optional and is not required to be provided by conforming implementations.

Noncompliant Code Example (POSIX)

In the following noncompliant code example, fmemopen() and open_memstream() are assumed to succeed. However, if the calls failsfail, the two file pointers in and out will be NULL null and the program has will have undefined behavior.

Code Block
bgColor#ffcccc
langc
int main(int argc, char *argv[])
{
FILE *out, *in;
 
if (argc != 2) {
	/* Handle error */
}
 
in = fmemopen(argv[1], strlen(argv[1]), "r"); /* violation */
/* Use in */
 
out = open_memstream(&ptr, &size); /* violation */
/* Use out */
 
}

...