主要内容

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

MISRA C:2012 Rule 21.20

The pointer returned by the Standard Library functions asctime, ctime, gmtime, localtime, localeconv, getenv, setlocale or strerror shall not be used following a subsequent call to the same function

描述

规则定义

The pointer returned by the Standard Library functions asctime, ctime, gmtime, localtime, localeconv, getenv, setlocale or strerror shall not be used following a subsequent call to the same function. 1

此规则来自 MISRA C™:2012 Amendment 1。

理由

前面的函数返回指向标准库中对象的指针。此对象的实现可以使用静态缓冲区,该缓冲区可以通过对同一函数的第二次调用进行修改。因此,在后续调用同一函数之前通过指针访问的值可能会发生意外更改。

故障排除

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

示例

全部展开

#include <stdio.h>
#include <locale.h>
#include <string.h>

void f1(void)
{
    const char* res1;
    const char* res2;
    char copy[ 128 ];
    res1 = setlocale(LC_ALL, 0);
    (void) strcpy(copy, res1);
    res2 = setlocale(LC_MONETARY, "French");
    printf("%s\n", res1);    /* Non-compliant */
    printf("%s\n", copy);    /* Compliant */
    printf("%s\n", res2);    /* Compliant */
}

在此示例中:

  • 第一个 printf 语句不符合条件,因为 setlocale 返回的指针是在为 res2 赋值时对其进行后续调用时使用的。

  • 第二个 printf 语句符合条件,因为 strcpy 执行的复制操作是在对 setlocale 函数的后续调用之前进行的。

  • 第三个 printf 语句符合条件,因为在使用该语句之前未对 setlocale 函数进行后续调用。

检查信息

组:标准库
类别:强制
AGC 类别:强制

版本历史记录

在 R2017a 中推出


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.