An empty infinite loop that does not do anything within the loop body is a suboptimal solution, and no code should use it. The solution is suboptimal because it consumes CPU cycles but does nothing. An optimizing compiler can remove such a loop, and it can lead to unexpected results. According to C1X Committee Draft \[[ISO/IEC 9899:201x|AA. Bibliography#ISO/IEC 9899-201x]\], Section 6.8.5.6 Wiki Markup
An iteration statement that performs no input/output operations does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression-3, may be assumed by the implementation to terminate.155
155) This is intended to allow compiler transformations, such as removal of empty loops, even when termination cannot be proven.
Noncompliant Code Example
...
Code Block | ||
---|---|---|
| ||
int main(void) { /* set up buffers, signal handlers for interrupts, etc. */ /* ... */ for ( ; ; ) { sleep(DURATION); /* let interrupt handler do all the work */ } /* not reached */ } void rcv_intr(int interrupt) { /* signal handler entered upon data_available interrupt */ /* ... */ get_packet(); /* read the packet */ if (packet.hdr.service == ICMP_ECHO) { send_packet(); /* send the packet */ } /* ... */ } |
Exceptions
MSC40MSC01-EX1EX0: In rare cases, use of an empty infinite loop may be unavoidable. For instance, an empty loop may be necessary on a platform that does not support sleep(3)
or an equivalent function. Another example occurs in operating system kernels. A task started before normal scheduler functionality is available may not have access to sleep(3)
or an equivalent function. In such a case, it is necessary to adopt alternative solutions that prevent an optimizing compiler from removing the empty infinite loop.
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC40 MSC01-C J | low | unlikely | medium | P2 | L3 |
Bibliography
Wiki Markup |
---|
\[[API 2006|https://www.securecoding.cert.org/confluence/display/java/AA.+Java+References#AA.JavaReferences-API06]\] |
...
SER03-J. Prevent serialization of unencrypted, sensitive data 16. Serialization (SER) SER05-J. Do not allow serialization and deserialization to bypass the Security Manager