...
Assertions should never be used to verify the absence of runtime (as opposed to logic) errors, such as
- invalid user input (including command line arguments and environment variables)
- file errors (for example, errors opening, reading or writing files)
- network errors (including network protocol errors)
- out of memory conditions (for example,
malloc()
or similar failures) - system resource exhaustion (for example, out of file descriptors, processes, threads)
- system call errors (for example, errors executing files, locking or unlocking mutexes)
- invalid permissions (for example, file, memory, user)
...
In particular, assertions are generally unsuitable for server programs or embedded systems in deployment. A failed assertion can lead to a denial-of-service attack if triggered by a malicious user, such as if size
were being, in some way, derived from client input. In such situations, a soft failure mode, such as writing to a log file and rejecting the request, is more appropriate.
Code Block | ||
---|---|---|
| ||
if (size > SIZE_MAX/sizeof(char *)) { fprintf( log_file, __FILE__ ": size %zu exceeds SIZE_MAX/sizeof(char *)\n", size ); size = SIZE_MAX/sizeof(char *); } table_size = size * sizeof(char *); |
...
The noncompliant code example below uses the assert()
macro to verify that memory allocation succeeded. Because memory availability depends on the overall state of the system and may can become exhausted at any point during a process lifetime, a robust program must be prepared to gracefully handle and recover from its exhaustion. Therefore, using the assert()
macro to verify that a memory allocation succeeded would be inappropriate as because doing so might lead to an abrupt termination of the process and open , opening up the possibility of a denial-of-service attack. See also guidelines recommendation MEM11-C. Do not assume infinite heap space and rule MEM32-C. Detect and handle memory allocation errors.
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: MSC11-CPP. Incorporate diagnostic tests using assertions
Bibliography
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 7.2.1, "Program diagnostics" Wiki Markup
Bibliography
...
MSC10-C. Character Encoding - UTF8 Related Issues 49. Miscellaneous (MSC) MSC12-C. Detect and remove code that has no effect