Thursday, March 25, 2010

Do not apply pointer arithmetic to pointers





Pointer arithmetic shall only be applied to pointers that address an array or array element (misra2004_17_1_PointerArithmeticOnNotPointers.rule)


Description:

"Pointer arithmetic shall only be applied to pointers that address an array or array element. Addition and subtraction of integers (including increment and decrement) from pointers that do not point to an array or array element results in undefined behaviour."

Benefits:

Rule makes the code more readable and less confusing.

Example:

void foo( int a[] ) {
   int* p1 = 0;
   int* p2;
   int* p3 = a;

   a++;     // OK
   p1++;    // Violation
   p2 = a;
   p2++;    // OK
   p3++;    // OK
}

Repair:

Do not apply pointer arithmetic to pointers.

References:
MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 17
Author
ParaSoft


Tags: Pointer arithmetic, less confusing, more readable
 

switch shall have at least one case




Every switch statement shall have at least one case clause (misra2004_15_5_AvoidSwitchWithNoCase.rule)


Description

Every switch statement shall have at least one case.

Benefits:

Provides maintainability of 'switch' statement.

Example:

void foo(int i)
{

   switch(i)      /* Violation */
   {

       default:
           ;
   }

}

Repair:

void foo(int i)
{
   switch(i)      /* OK */
   {
     case 1:
     {

     }
     default:
           ;

   }

}

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 15

Author
ParaSoft
 
 
 
Tags: switch, case, maintainability, Guidelines, critical systems
 
 

Do not convert pointer to pointer




A cast should not be performed between a pointer to object type and a different pointer to object type (misra2004_11_4_DoNotConvertPointerToPointer.rule)


Description:

"A cast should not be performed between a pointer to object type and a different pointer to object type. Conversions of this type may be invalid if the new pointer type requires a stricter alignment."

Note: This rule skips casting of void type.

Benefits:

Prevents incorrect pointer alignment.

Example:

void foo( ) {
   int* pi;
   char* i;

   i = (char*) pi; // Violation
   i = (char*) &i; // Violation
}

Repair:

Do not convert pointer to different pointer.

References:
MISRA-C:2004 Guidelines for the use of the C language in critical systems
Chapter 6, Section 11

Author
ParaSoft


Tags: cast, pointer, void, pointer alignment, MISRA, critical systems


Avoid using unsafe string functions




Avoid using unsafe string functions (UsageOfStringFunctions.rule)


Description

This rule detects code that uses unsafe string functions from C library.

Benefits:

Prevents the use of functions which may cause buffer overflows.

According to David A. Wheeler (see reference below), "C functions users must avoid using dangerous functions that do not check bounds unless they've ensured that the bounds will never get exceed.

Functions to avoid in most cases (or ensure protection) include the functions strcpy(), strcat(), sprintf() (with cousin vsprintf()), and gets().

These should be replaced with functions such as strncpy(), strncat(), snprintf(), fgets(), respectively."

Example:

#include
void main( void )
{
char* str1 = "testcase";
char* str2 = "testcase";
char* str3=0;

str3 = strcat( str1, str2 ); // Violation
}

Repair:

#include
void main( void )
{
char* str1 = "testcase";
char* str2 = "testcase";
char* str3=0;

str3 = strncat( str1, str2, 16 ); // OK
}

References:
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/dangers-c.html

Author
ParaSoft


Tags: Avoid, unsafe, string, function, unsafe string, C library, buffer overflows, dangerous functions, strncpy, strncat, snprintf, fgets


Wednesday, March 24, 2010

Modular programming in C




What is Modular programming ?

- A programming technique to break down program functions into separate modules/parts/layers.
- Module, have to accomplishes one function by containing the source codes and input/output variables needed to accomplish that function.

Tuesday, March 23, 2010

Do NOT check floats for equality




Don't check floats for equality; check for greater than or less than (EqualityFloatLeft.rule)


Description:
This rule checks whether you check floats for equality instead of checking for greater than or less than.

Benefits:

If you check floats for equality, you make your code more susceptible to rounding errors.

Example:

void func(float a, int b)
{
   if (a==b) { }     // Violation

   while (a!=b) { }  // Violation
}



Repair:

void func(float a, int b)
{
   if (a>=b) { }     // OK

   while (a<=b) { }  // OK
}

Author
ParaSoft


My comment for repairing:

void func(const float a, const int b)
{
    if ( a > b ) { }
    else if ( a < b ) {}
    else {}
    // while (a > b) { };
    // while (a < b) { };
}

Ref: http://www.c-faq.com/fp/fpequal.html
Tags: vav.vn, vav, float, float equality, check float values equality, floating point, absolute, epsilon






domain co.cc




http://www.zebrazone.co.cc/,
http://www.fansipan.co.cc/,
http://www.zebrazoo.co.cc/

altonjuve_shift_2_yahoo_dot_com



Avoid Directly Access Globals




Do not directly access global data from a constructor (AvoidDirectlyAccessGlobals.rule)


Description:

Directly accessing global data from a constructor is risky because the global object may not yet exist when the "other" static object is initialized. This rule detects if you directly access global data from a constructor.

Function call order




The value of an expression shall be the same under any order of evaluation that the standard permits (misra2004_12_2_4_FunctionsCallOrder.rule)


Description

"Apart from a few operators (notably the function call operator (), &&, , ?: and , (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. This means that no reliance can be placed on the order of evaluation of sub-expressions, and in particular no reliance can be placed on the order in which side effects occur. Those points in the evaluation of an expression at which all previous side effects can be guaranteed to have taken place are called “sequence points”. Sequence points and side effects are described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].

Note that the order of evaluation problem is not solved by the use of parentheses, as this is not a precedence issue." "Functions may have additional effects when they are called (e.g. modifying some global data). Dependence on order of evaluation could be avoided by invoking the function prior to the expression that uses it, making use of a temporary variable for the value.

Monday, March 22, 2010

Avoid indexing pointer




Array indexing shall be the only allowed form of pointer arithmetic (misra2004_17_4_AvoidIndexingPointerAsArray.rule)


Description:

"Array indexing is the only acceptable form of pointer arithmetic, because it is clearer and hence less error prone than pointer manipulation. This rule bans the explicit calculation of pointer values. Array indexing shall only be applied to objects defined as an array type. Any explicitly calculated pointer value has the potential to access unintended or invalid memory addresses. Pointers may go out of bounds of arrays or structures, or may even point to effectively arbitrary locations."

Drawbacks: For more complex code rule may not be able to check if there is indexed pointer which points to array. For such cases the rule may report false positives.

Dev-cpp: stray '\160' in program




The message "stray '\160' in program" when building by Dev-Cpp is occurred when using "Copy and Paste" action.

So, finally, DO NOT copy and paste source code. Please type line by line.


Avoid assignment in if




Avoid assignment in if statement condition (IfAssign.rule)


Description:

This rule checks whether your code has assignment within an if statement condition. This rule is enabled by default.

Benefits:

Legibility and maintainability.

Assignment in the context of an if statement is easily confused with equality.

Example:

void foo(int a, int b) {

  if ( a = b ) {}  // Violation

}

Repair:

void foo(int a, int b) {

  if ( a == b ) {} // OK
}

Author
ParaSoft




Avoid nested assignment statements





The value of an expression shall be the same under any order of evaluation that the standard permits (misra2004_12_2_5_AvoidNestedAssignment.rule)


Description

"Apart from a few operators (notably the function call operator (), &&, , ?: and , (comma)) the order in which sub-expressions are evaluated is unspecified and can vary. This means that no reliance can be placed on the order of evaluation of sub-expressions, and in particular no reliance can be placed on the order in which side effects occur. Those points in the evaluation of an expression at which all previous side effects can be guaranteed to have taken place are called “sequence points”. Sequence points and side effects are described in sections 5.1.2.3, 6.3 and 6.6 of ISO 9899:1990 [2].

Note that the order of evaluation problem is not solved by the use of parentheses, as this is not a precedence issue."

"Assignments nested within expressions cause additional side effects. The best way to avoid any chance of this leading to a dependence on order of evaluation is to not embed assignments within expressions.

For example, the following is not recommended:

x = y = y = z / 3;

x = y = y++;"

Benefits:

Rule prevents evaluation of expression dependent on compiler version.

Example:

void foo( int x, int y, int z ) {

   x = y = z / 3;  // Violation
}

Repair:

void foo( int x, int y, int z ) {
   y = z / 3;  // OK
   x = y;      // OK
}

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 12

Author
ParaSoft

Struct vs Union




A structure is a collection of items of different types; and each data item will have its own memory location.

An union allocates for each item in a shared memory location i.e., only one memory location will be shared by the data items of union. Size of union will be the size of the biggest variable.





Do not reuse typedef names




Do not reuse typedef names (misra2004_5_3_DoNotReuseTypedefNames.rule)


Description

Typedef names shall not be reused.

Benefits:

Reuse of typedef names can lead to errors and confusion.

Example:

typedef int MyInt;
void foo()
{
 double MyInt;  /* Violation */
}

Repair:
typedef int MyInt;
void foo()
{
 double MyVar;  /* OK */
}

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 5

Author
ParaSoft



Do not mix bit-fields




Do not mix bit-fields other data within the same structure (misra2004_3_5_BitFieldStructuresWithoutOtherData.rule)


Description

It is recommended that structures should be declared specifically to hold the sets of bit fields, and do not include any other data within the same structure.

Benefits:

Rule prevents from the potential pitfalls and areas of implementation-defined (i.e.non-portable) behaviour.

Example:

struct message {  /* Violation */
   signed int little: 4;
   unsigned int x_set: 1;

   int size;
};

Repair:

struct message {  /* OK */
   signed int little: 4;
   unsigned int x_set: 1;
};

References:

MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 3

Author
ParaSoft


error information shall be tested




Violations:
misra2004-16_10: If a function returns error information, then that error information shall be tested

Description:

"A function (whether it is part of the standard library, a third party library or a user defined function) may provide some means of indicating the occurrence of an error. This may be via an error flag, some special return value or some other means. Whenever such a mechanism is provided by a function the calling program shall check for the indication of an error as soon as the function returns.

However, note that the checking of input values to functions is considered a more robust means of error prevention than trying to detect errors after the function has completed (see Rule 20.3). Note also that the use of errno (to return error information from functions) is clumsy and should be used with care (see Rule 20.5)."

Note:
Rules checks usage of function calls which returns int value and reports violation when this value is not assigned or checked.

Benefits:
Rule helps writing safety code.

Example:

int SomeFunctionReturningError( );

void foo( )  {
   SomeFunctionReturningError( );  // Violation
}

Repair:

int SomeFunctionReturningError( );

int foo( )  {

   int x;
   x = SomeFunctionReturningError( );        // OK
   if (SomeFunctionReturningError( ));       // OK

   switch (SomeFunctionReturningError( )) {  // OK

   }

   return SomeFunctionReturningError( );     // OK
}

References:
MISRA-C:2004 Guidelines for the use of the C language in critical systems

Chapter 6, Section 16

Author
ParaSoft


Friday, March 19, 2010

Visual Studio Project Converter



Change to vspc folder:
Run command: vspc ["from version" "to version" "fileName" [/option --longOption]] 
e.g: vspc VS2008 VS2005 D:\MyPrj\TestPrj.sln /b /r
 
=> Convert "TestPrj" solution and "TestPrj" project files from VS2008 downto VS2005 with backup and importing references options.
 
More details:
 
Visual Studio .NET solutions converter v.0.9.3
Totally Free(tf:-) by Stoyan Damov. Modified by Nikolay Samofatov

Usage: vspc ["from version" "to version" "fileName" [/option --longOption]]
and : One of the following - VS2002, VS2003, VS2005 or VS2008.

Note that conversion of .NET projects for version 2005 and 2008 is currently not supported. Native C++ projects should convert just fine between any of the above versions.

: The full solution/project file path (all projects in the solution are converted automatically, and I don't think you'll want a separate option on the command line to avoid that:)

LANGUAGE-INDEPENDENT OPTIONS

/q, --quiet Do not display anything on the console

/b, --backup Backup each converted file

C#/VB.NET-SPECIFIC OPTIONS

/h, --hintpaths The framework version of the project references (in HintPath) is converted to the default one for the VS project (i.e. 2002 gets version v1.0.3705, 2003 gets v1.1.4322)

/w, --webprojects Convert the web applications projects, found in the solution file;

VC++.NET-SPECIFIC OPTIONS

/p, --relativepaths Fix the "RelativePath" attribute to prepend ".\"

/r, --references Import references, i.e. convert , added by "Add Reference" to include the appropriate .DLLs in stdafx.h, i.e. "#using "... (if the option is missing, you'll be able to open the project, but will have to add the #using clauses by hand)

/c, --nochkclr Remove the "nochkclr.obj" dependency in the linker settings from 2002 projects, add it to 2003 projects (use the option or your project won't compile, unless you have that file)

VC++.NET NOTE:

Visual C++ 2002 (DUH!) DOES NOT support ".resx" files, and refuses to load projects with such files, so I remove them from the project files



Thursday, March 18, 2010

ParaSoft C++Test: Precompile failed



Process exited with code -1073741515


C++Test cannot see cl.exe (with Visual Studio), gcc (with Linux) and its dependencies.

How to fix:
-------- + Make sure that PATH environment is set. We can test the PATH by cmd.exe or shell (env command). Run cl.exe --version to check the path and its dependencies.
-------- + Maybe add $(INSTALL_DIR)\Microsoft Visual Studio 8\Common7\IDE if mspdb80.dll was not found by cl.exe.




Tags: -1073741515, 1073741515, C++Test, parasoft, Precompile, Error, error result, cl.exe, error code, exit code, from cl, visual studio


mspdb80.dll was not found




Set PATH environment: add more $(INSTALL_DIR)\Microsoft Visual Studio 8\Common7\IDE.
e.g: I searched and saw mspdb80.dll in C:\Program Files\Microsoft Visual Studio 8\Common7\IDE



Labels