CXX.SIZEOF.CSTRING

Use of sizeof on char* may be misleading

The sizeof operator returns the size of its operand argument in bytes. In the case of a char pointer, it is the size of the pointer type and not the size of the string that is returned as the name is misleading. To get the length of a char* string, use the appropriate C library function.

Vulnerability and risk

Incorrect calculations of string sizes can lead to many types of security vulnerabilities.

Mitigation and prevention

Avoid using sizeof(char *).

Vulnerable code example

Copy
int str_len (char* text)
{
  int len = sizeof(text);
  return len;
}

The use of sizeof on a char* produces the size of the pointer type and not the size of the string, which is misleading.

Security training

Application security training materials provided by Secure Code Warrior.