There are two basic approaches for managing null-terminated byte strings in C programs. The first is the static approach, where strings are maintained in statically allocated arrays. The second approach is the dynamic approach, where memory is allocated as required. Each approach has advantages and disadvantages. However, it generally makes sense to select a single approach to managing strings and apply it consistently across a project. Otherwise, the decision is left to individual programmers who are likely to make different, inconsistent choices.
Statically allocated strings assumes a fixed size character array, meaning that it is impossible to add data after buffer is filled. Because the static approach discards excess data, actual program data can be lost. Consequently, the resulting string must be fully validated.
Dynamically allocated buffers dynamically resize as additional memory is required. Dynamic approaches scale better and do not discard excess data. The major disadvantage is that if inputs are not limited they can exhaust memory on a machine consequently be used in denial-of-service attacks.
Wiki Markup |
---|
Dynamical allocation is often disallowed in safety critical systems. For example, the MISRA standard includes Rule 20.4 that requires that "Dynamic heap memory allocation shall not be used" \[[MISRA 04|AA. C References#MISRA 04]\]. Some safety critical systems can take advantage of dynamic memory allocation during initialization, but not during operations. For example, avionics software may dynamically allocate memory while initializing the aircraft, but not during flight. |
Wiki Markup |
---|
There are a number of existing libraries available for managing string data; the library selected depends on the overall approach adopted for managing null-terminated byte strings. The functions defined by C99 Section 7.21, "String handling <string.h>" \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] are primarily intended for managing statically allocated strings. |
Wiki Markup |
---|
The managed string library described in \[[Burch 06|AA. C References#Burch06]\] was developed in response to the need for a string library that could improve the quality and security of newly developed C language programs while eliminating obstacles to widespread adoption and possible standardization. |
...
Wiki Markup |
---|
\[[Burch 06|AA. C References#Burch06]\]
\[[CERT 06c|AA. C References#CERT 06c]\]
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.21, "String handling <string.h>"
\[[MISRA 04|AA. C References#MISRA 04]\] Rule 20.4
\[[Seacord 05a|AA. C References#Seacord 05a]\] Chapter 2, "Strings" |
...