CXX.OVERWRITE_CONST_CHAR

Attempt to overwrite a constant string

Whenever a string literal is assigned to a pointer to a non-const character variable, it should be validated for its constant-ness before modifying its value, because memory containing string literals cannot be modified either in part or in full.

The CXX.OVERWRITE_CONST_CHAR checker flags code that tries to modify the string literal assigned to any pointer to non-const character variable.

Vulnerability and risk

Modifying a string literal is an undefined behavior. It may result in access violation errors since they are frequently stored in read-only memory.

Mitigation and prevention

The simplest way to prevent this defect is to copy the string literal to a non-const memory, either on stack or on heap, and then modify the non const copy.

Vulnerable code example

Copy
   #include <string.h>
    
   int var (int);
    
   int var (int isKnown)
   {
       unsigned char * obj = "";  
       if (isKnown) 
       {
          strcpy(obj, "known"); 
          // Writing over read-only string 
      }
      else 
      {
          strcpy(obj, "unknown"); 
      }
      return 0;
  }

In this example, ‘obj’ is a pointer of the char type variable and it is assigned with “” (const type of string). Then, we are trying to copy another string to the ‘obj’ variable, which can lead to an access violation error. Klocwork reports this vulnerability as a CXX.OVERWRITE_CONST_CHAR defect at lines 10 and 15 indicating “Attempt to overwrite a string literal”.

Fixed code example

Copy
   #include <string.h>
    
   int var (int);
    
   int var (int isKnown)
   {
       unsigned char obj[10] = "";  
       if (isKnown) 
       {
          strcpy(obj, "known"); 
          // Now writing over non-const string 
      }
      else 
      {
          strcpy(obj, "unknown"); 
      }
      return 0;
  }

In the fixed code example, ‘obj’ is now an array of character and the assignment on line 7 is a copy of the empty string literal to the memory for the array. When the modification occurs on lines 10 or 15, the modification is made on non-const memory.