Main Content

CWE Rule 500

Public Static Field Not Marked Final

Since R2023a

Description

Rule Description

An object contains a public static field that is not marked final, which might allow it to be modified in unexpected ways.

Polyspace Implementation

The rule checker checks for Public static field not const.

Examples

expand all

Issue

This issue occurs when all of these conditions are true:

  • A class contains a data member that is both static and public

  • The static and public data member is not const

Risk

The public static data members of a class can be modified by any of class in the program. Unless public static data members are specified as const, they might be modified in unexpected ways and result in bugs that are difficult to diagnose.

Fix

To resolve this defect, specify the public static data members as const or constexpr.

Example — Avoid Nonconst public static Data Members
#include<string>
class SomeAppClass {

private:
	static std::string appPropertiesConfigFilep2; 
	
protected:
	static std::string appPropertiesConfigFilepr2; 
	
public:
	static std::string appPropertiesConfigFile2;  //Noncompliant
	
	static void foo() {}          
	int bar() {
		static int v = 3;
		return v;
	}
};

In this example, the data member appPropertiesConfigFile2 is static and public, but not const. Polyspace® flags the member. The static data members that are private and protected are not flagged. This rule does not apply to static objects that are in the scope of public member functions of a class.

Correction — Declare public static Data Members as const

To resolve this defect, declare the public static data members of a class as const.

#include<string>
class SomeAppClass {

private:
	static std::string appPropertiesConfigFilep2; 
	
protected:
	static std::string appPropertiesConfigFilepr2; 
	
public:
	static const std::string appPropertiesConfigFile2; //No Defect
		
	static void foo() {}          
	int bar() {
		static int v = 3;
		return v;
	}
};

Check Information

Category: Others

Version History

Introduced in R2023a