...
| Code Block |
|---|
int calculate_size(char *str) {
/* calculates the size of a string */
}
int main() {
size_t s = calculate_size(argv[1]);
char *my_str = malloc(s);
if (str != 0) {
/* process string */
}
}
|
...
To correct this problem it is necessary to ensure that size parameters to allocation routines are stored consistently. In the example below, the calculate_size() routine has been modified to return a size_t type.
| Code Block |
|---|
size_t calculate_size(char *str) {
/* calculates the size of a string */
}
int main() {
size_t s = calculate_size(argv[1]);
char *my_str = malloc(s);
if (str != 0) {
/* process string */
}
}
|
with an unexpected size.
To prevent this error, size parameters should not be operated on in a way that they are transferred and stored in different data types. Furthermore, size parameters should be checked for integer conversion errors before they are supplied to malloc(), calloc(), or realloc().
To prevent this error, size parameters should not be operated on in a way that they are transferred and stored in different data types. Furthermore, size parameters should be checked for integer conversion errors before they are supplied to malloc(), calloc(), or realloc().
Non-compliant Code Example 1
In this example, the calculate_size() routine is used to determine how much memory to allocate to store a user-supplied string.
The result of calculate_size() is used to allocate memory for a buffer to hold the user-supplied string. However, the value returned by calculate_size() is of a signed integer type. When this value is stored in the variable s, its value may may resolve to an unexpected value. This error leads to the allocation of memory with an unexpected size.
| Code Block |
|---|
int calculate_size(char *str) { /* calculates the size of a string */ } int main() { size_t s = calculate_size(argv[1]); char *my_str = malloc(s); if (str != 0) { /* process string */ } } |
...
| Code Block |
|---|
size_t calculate_size(char *str) {
/* calculates the size of a string */
}
int main() {
size_t s = calculate_size(argv[1]);
char *my_str = malloc(s);
if (str != 0) {
/* process string */
}
}
|
...