V518. The 'malloc' function allocates strange amount of memory calculated by 'strlen(expr)'. Perhaps the correct variant is strlen(expr) + 1

19.11.2010

The analyzer found a potential error related to allocating insufficient amount of memory. The string's length is calculated in code and the memory buffer of a corresponding size is allocated but the terminal '\0' is not allowed for.

Consider this example:

char *p = (char *)malloc(strlen(src));
strcpy(p, src);

In this case, it is just +1 which is missing. The correct version is:

char *p = (char *)malloc(strlen(src) + 1);
strcpy(p, src);

Here is another example of incorrect code detected by the analyzer in one application:

if((t=(char *)realloc(next->name, strlen(name+1))))
{
  next->name=t;
  strcpy(next->name,name);
}

The programmer was inattentive and made a mistake when writing the right bracket ')'. As a result, we will allocate 2 bytes less memory than necessary. This is the correct code:

if((t=(char *)realloc(next->name, strlen(name)+1)))
You can look at examples of errors from real projects which were detected by this diagnostic message.