C & C++

C & C++

Made by DeepSource

Use of memset with possibly unintended behaviour CXX-W2048

Bug risk
Major

Found potential mistakes in memset() calls that can lead to unintended behavior.

The following cases will be considered potentially unintended usage of the API memset:

  • invoking memset with non-char pointer array as the first argument and character zero, '0', as the second argument in place of integer zero. Consider using the integer value zero.

  • invoking memset with the second argument with a value that will overflow. Consider using the value within the range of unsigned char because the second argument is converted from int to unsigned char.

  • invoking memset to fill no bytes, i.e. zero as the final argument. Do you mean to swap the second and the third argument in this case?

To fix the issue use the following API signature and apply the apply the solution as discussed above. void* memset(void* destination, int fill_value, size_t byte_count)

Bad practice

void foo() {
  int i[5] = {1, 2, 3, 4, 5};
  int *ip = i;
  char c = '1';
  char *cp = &c;
  int v = 0;

  // Case 1
  memset(ip, '0', 1); // suspicious

  // Case 2
  memset(ip, 0xabcd, 1); // fill value gets truncated

  // Case 3
  memset(ip, sizeof(int), v); // zero length, potentially swapped
}

Recommended

void foo() {
  int i[5] = {1, 2, 3, 4, 5};
  int *ip = i;
  char c = '1';
  char *cp = &c;
  int v = 0;

  // Case 1
  memset(ip, 0, 1); // use integer zero

  // Case 2
  memset(ip, 0x00, 1); // use fill value within unsigned character range

  // Case 3
  memset(ip, v, sizeof(int)); // swap the arguments
}

References