BUG OF THE MONTH | Memory error

PVS-Studio warning: V527 It is odd that the ‘\0’ value is assigned to ‘char’ type pointer. Probably meant: *body[new_len] = ‘\0’. http_request.c 370

Software weaknesses type – CWE-787: Out-of-bounds Write

int _read_request_body(http_transaction_h http_transaction,
                       char **body)
  *body = realloc(*body, new_len + 1);
  memcpy(*body + curr_len, ptr, body_size);
  body[new_len] = '\0';                       
  curr_len = new_len;

The function takes a pointer to a pointer. This allows to reallocate the memory and return the address of a new string.

The error is in the line:

body[new_len] = '\0';

It turns out that a pointer to a pointer is interpreted as an array of pointers. There is no array of course. That’s why NULL (‘\0’ in this case is interpreted as a null pointer) will be written out of place. Some unknown memory block gets damaged.

In addition, there is another error. The line won’t end with a terminal null. So, the situation isn’t really great.

Correct code:

(*body)[new_len] = '\0';

Please click here to see more bugs from this project.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.