I've spotted the following piece of C code, marked as BAD (aka buffer overflow bad). The problem is I don't quite get why? The input string length is captured before the allocation etc.
char *my_strdup(const char *s)
{
size_t len = strlen(s) + 1;
char *c = malloc(len);
if (c) {
strcpy(c, s); // BAD
}
return c;
}
Update from comments:
- the 'BAD' marker is not precise, the code is not bad, not efficient yes, risky (below) yes,
- why risky?
+1after the strlen() call is required to safely allocate the space on heap that also will keep the string terminator ('\0')