Main Content

MISRA C:2023 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

Since R2024a

Description

Rule Definition

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.

This rule comes from MISRA C™: 2012 Amendment 1.

Rationale

The preceding functions return a pointer to an object within the Standard Library. Implementation for this object can use a static buffer that can be modified by a second call to the same function. Therefore the value accessed through a pointer before a subsequent call to the same function can change unexpectedly.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#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 */
}

In this example:

  • The first printf statement is non-compliant because the pointer returned by setlocale is used following a subsequent call to it when res2 is assigned.

  • The second printf statement is compliant because the copy operation performed by strcpy is made before a subsequent call to setlocale function is made.

  • The third printf statement is compliant because there is no subsequent call to the setlocale function is made before use.

Check Information

Group: Standard libraries
Category: Mandatory
AGC Category: Mandatory

Version History

Introduced in R2024a