MEM-malloc-strlen
In this section:
Synopsis
Dangerous arithmetic with strlen in argument to malloc.
Enabled by default
No
Severity/Certainty
Medium/Medium

Full description
Dangerous arithmetic with strlen in an argument to malloc. It is usual to allocate a new string using malloc(strlen(s)+1), to allow for the null terminator. However, it is easy to type malloc(strlen(s+1)) by mistake, leading to strlen returning a length one less than the length of s, or if s is empty, exhibit undefined behavior.
Coding standards
- CWE 131
Incorrect Calculation of Buffer Size
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
#include <string.h>
void example(char *s) {
char *a = malloc(strlen(s+1));
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
#include <string.h>
void example(char *s) {
char *a = malloc(strlen(s)+1);
}