...
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 NULL
null. 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 |
|
---|---|---|---|
| pointer Pointer to a |
|
|
| pointer Pointer to a |
|
|
|
| Unchanged 2 |
SettingAnchor 1 1 errno
is a POSIX [ISO/IEC 9945:2008] extension to the C Standard.
On error,Anchor 2 2 posix_memalign()
returns a value that corresponds to one of the constants defined in the<errno.h>
header. The function does not seterrno
. Theposix_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 | ||||
---|---|---|---|---|
| ||||
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 */ } |
...