主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2023 Rule 7.4

A string literal shall not be assigned to an object unless the object’s type is “pointer to const-qualified char”

自 R2024a 起

描述

规则定义

A string literal shall not be assigned to an object unless the object’s type is “pointer to const-qualified char” 1 .

理由

此规则可防止允许修改字符串字面值的赋值。

尝试修改字符串字面值可能会导致未定义的行为。例如,某些实现可以将字符串字面值存储在只读内存中。尝试修改字符串字面值可能会导致异常或崩溃。

作为例外,通过可变参量列表将字符串字面值传递给变参函数并不违反此规则。

Polyspace 实现

规则检查项将字符串字面值的赋值标记为:

  • 数据类型不是 const char* 的指针。

  • 数据类型不是 const char 的数组。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

char *str1 = "xxxxxx";            // Noncompliant 
const char *str2 = "xxxxxx";      // Compliant 

void checkSystem1(char*);
void checkSystem2(const char*);

void main() {
 checkSystem1("xxxxxx");    // Noncompliant 
 checkSystem2("xxxxxx");    // Compliant 
}

在此示例中,如果将字符串字面值直接或通过函数参量的副本赋值给 const char* 指针,便不会违反规则。仅当未使用 const 限定符时,才会违反规则。

在此示例中,字符串字面值被传递给变参函数 foobar。由于字符串字面值作为可变参量列表的一部分被传递给 foo,因此 Polyspace® 不会报告违规。对于 bar,字符串字面值参量绑定到 char*,这不符合此规则。Polyspace 会报告 bar 违规。

extern void foo( int x, ... );

extern void bar( char *text, ... ); 

void variadic( void )
{
    foo( 42u, "String Literal" ); // Compliant by exception
    bar( "String Literal", 42u ); // Noncompliant
}

检查信息

组:字面值和常量
类别:必需
AGC 类别:必需

版本历史记录

在 R2024a 中推出

全部展开


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.