这里没有软件测试的泛泛理论,只有博主的最佳实践。 博主的研究方向为静态分析和性能测试,致力于各种测试工具的引入、评估和开发。 本博的测试文章均为作者原创,转载请务必注明出处。

C语言编程规则解析-19.6、20.8—20.12

上一篇 / 下一篇  2008-06-27 14:03:27 / 个人分类:静态分析

19.6 不要使用#undef

描述:通常情况下不应该使用#undef,它在代码中的使用会引起和已有的宏或其意义的混淆。

好处:该规则可以提高代码的可读性和可维护性。

举例:

#define  L      0
#undef   L              /* Violation */

extern S16 test_1906( void )
{
   return 1;
}

20.9 产品代码中不要使用<stdio.h>

描述:

包括文件函数和I/O函数——fgetpos, fopen, ftell, gets, perror, remove, rename, and ungetc。流和文件I/O中有大量未详细说明、未定义以及由实际环境决定的行为(函数)。通常情况下,嵌入式系统的产品代码中不需要他们。

举例:
#include <stdio.h>                  /* Violation */

extern S16 test_2009( void )
{
   FILE *fp;

   fp = fopen( "test", "r" );

   return 0;
}

20.12 不要使用<time.h>库中的时间处理函数

描述:该库和时钟相关,不同的方面互相依赖或者没有详细说明,例如时间的格式等。如果要使用time.h库中的任何东东,一定要清楚所使用的编译器的精确实现过程。

举例:

#include <time.h>                /* Violation */

extern S16 test_2012( void )
{
  S16    r = 0;
  time_t xtime;
 
  if ( time( &xtime ) == ( time_t )-1 )  /* Violation */
  {
      r = -1;
  }

  return r;
}

20.11 不要使用<stdlib.h>中的库函数abort, exit, getenv and system

描述:嵌入式系统中通常不需要这些函数,因为它不需要和环境通信。如果应用中有必要使用这些函数,一定要认真检查这些函数在实际环境中的行为。

举例:

#include  <stdlib.h>
void foo( void ) {
    char *libvar;
    libvar = getenv( "LIB" );  /* Violation */
    system( "dir" );           /* Violation */
    abort( );                  /* Violation */
    exit( 0 );                 /* Violation */
}

20.10 不要使用<stdlib.h>中的库函数atof, atoi and atol.

描述:当字符串不能转化时,这些函数会产生不可预知的行为。

举例:

#include <stdlib.h>
void foo( void ) {
    char *s; double x; int i; long l;
    s = "  -2309.12E-15";   
    x = atof( s );           /* Violation */
    s = "  -9885 pigs";     
    i = atoi( s );           /* Violation */
    s = "98854 dollars";    
    l = atol( s );           /* Violation */
}


20.8 不要使用信号处理库<signal.h>.

描述:该库中包含了和实际环境相关、未定义的行为。

举例:

#include <signal.h>             /* Violation */

extern S16 test_2008( void )
{
   S16 i = SIGINT;

   return i;
}

(未完,待续)

注:以上规则参考了c++test和QAC MISRA的内容。


TAG: 静态分析

 

评分:0

我来说两句

Open Toolbar