An object of type void *
is a generic data pointer. It can point to any data object. For any incomplete or object type T
, C permits implicit conversion from T *
to void *
or from void *
to T *
. The standard C library uses void *
to declare parameters and return types of functions designed to work for objects of different types. Such is the case with the standard C Standard memory allocation functions aligned_alloc()
, malloc()
, calloc()
, and realloc()
use void *
to declare parameters and return types of functions designed to work for objects of different types.
For example, the C library declares malloc()
as
...
Calling malloc(s)
allocates memory for an object whose size is s
and returns either a null pointer or a pointer to the allocated memory. A program can implicitly convert the pointer that malloc()
returns into a different pointer type.
Because objects returned by the C Standard memory allocation functions are implicitly converted into any object type, we recommend casting the results of these functions into a pointer of the allocated type because it increases the chances that the compiler will catch and diagnose a mismatch between the intended type of the object and the actual type of the object.
Noncompliant Code Example
...
A small collection of macros can provide secure implementations for common uses for the standard memory allocation functions. The omission of a REALLOC()
macro is intentional. (See void MEM08-C. Use realloc() only to resize dynamically allocated arrays.)
Code Block | ||||
---|---|---|---|---|
| ||||
/* Allocates a single object using malloc() */ #define MALLOC(type) ((type *)malloc(sizeof(type))) /* Allocates an array of objects using malloc() */ #define MALLOC_ARRAY(number, type) \ ((type *)malloc((number) * sizeof(type))) /* * Allocates a single object with a flexible * array member using malloc(). */ #define MALLOC_FLEX(stype, number, etype) \ ((stype *)malloc(sizeof(stype) \ + (number) * sizeof(etype))) /* Allocates an array of objects using calloc() */ #define CALLOC(number, type) \ ((type *)calloc(number, sizeof(type))) /* Reallocates an array of objects using realloc() */ #define REALLOC_ARRAY(pointer, number, type) \ ((type *)realloc(pointer, (number) * sizeof(type))) /* * Reallocates a single object with a flexible * array member using realloc(). */ #define REALLOC_FLEX(pointer, stype, number, etype) \ ((stype *)realloc(pointer, sizeof(stype) \ + (number) * sizeof(etype))) |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
|
| Can detect some violations of this recommendation when checking EXP36-C. Do not convert cast pointers into more strictly aligned pointer types | |||||||
ECLAIR |
| CC2.MEM02 | Fully implemented | ||||||
5.0 |
| Can detect violations of this rule with CERT C Rule Pack | |||||||
|
|
| |||||||
PRQA QA-C |
| 0695 | Fully implemented |
...