主要内容

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

MISRA C:2012 Dir 4.12

Dynamic memory allocation shall not be used

描述

规则定义

Dynamic memory allocation shall not be used 1 .

理由

使用标准库或第三方库提供的动态内存分配和释放例程可能会导致未定义行为。例如:

  • 您使用了 free 释放未通过 malloccallocrealloc 分配的内存。

  • 您使用了指向已释放内存位置的指针。

  • 您访问了未存储任何值的已分配内存。

第三方库提供的动态内存分配和释放例程很可能会出现类似的未定义行为。

如果您选择使用动态内存分配和释放例程,请确保您的程序行为是可预测的。例如,确保能安全处理因内存不足导致的分配失败。

故障排除

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

示例

全部展开

#include <stdlib.h>

static int foo(void);

typedef struct struct_1 {
    int a;
    char c;
} S_1;

static int foo(void) {

    S_1 * ad_1;
    int  * ad_2;
    int  * ad_3;

    ad_1 = (S_1*)calloc(100U, sizeof(S_1));        /* Non-compliant */
    ad_2 = malloc(100U * sizeof(int));             /* Non-compliant */
    ad_3 = realloc(ad_3, 60U * sizeof(long));      /* Non-compliant */

    free(ad_1);                                    /* Non-compliant */
    free(ad_2);                                    /* Non-compliant */
    free(ad_3);                                    /* Non-compliant */

    return 1;
}

在此示例中,当使用函数 malloccallocreallocfree 时,违反了该规则。

检查信息

组:代码设计
类别:必需
AGC 类别:必需

版本历史记录

在 R2019b 中推出


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.