V568. It's odd that the argument of sizeof() operator is the expression

01.03.2011

The analyzer detected a potential error: a suspicious expression serves as an argument of the sizeof() operator. Suspicious expressions can be arranged in two groups:

1. An expression attempts to change some variable.

The sizeof() operator calculates the expression's type and returns the size of this type. But the expression itself is not calculated. Here is a sample of suspicious code:

int A;
...
size_t size = sizeof(A++);

This code does not increment the 'A' variable. If you need to increment 'A', you'd better rewrite the code in the following way:

size_t size = sizeof(A);
A++;

2. Operations of addition, multiplication and the like are used in the expression.

Complex expressions signal errors. These errors are usually related to misprints. For example:

SendDlgItemMessage(
  hwndDlg, RULE_INPUT_1 + i, WM_GETTEXT,
  sizeof(buff - 1), (LPARAM) input_buff);

The programmer wrote "sizeof(buff - 1)" instead of "sizeof(buff) - 1". This is the correct code:

SendDlgItemMessage(
  hwndDlg, RULE_INPUT_1 + i, WM_GETTEXT,
  sizeof(buff) - 1, (LPARAM) input_buff);

Here is another sample of a misprint in program text:

memset(tcmpt->stepsizes, 0,
  sizeof(tcmpt->numstepsizes * sizeof(uint_fast16_t)));

The correct code:

memset(tcmpt->stepsizes, 0,
  tcmpt->numstepsizes * sizeof(uint_fast16_t));
You can look at examples of errors from real projects which were detected by this diagnostic message.