主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 22.2

A block of memory shall only be freed if it was allocated by means of a Standard Library function

描述

规则定义

A block of memory shall only be freed if it was allocated by means of a Standard Library function. 1

理由

分配内存的标准库函数为 malloccallocrealloc

当您将模块的地址传递给 freerealloc 函数时,您将释放该模块的内存。以下情况会导致未定义行为:

  • 您释放了一个未分配的内存模块。

  • 您释放了一个已经释放过的内存模块。

Polyspace 实现

您只能使用 Bug Finder 分析来检查此规则。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#include <stdlib.h>

void func1(void) {
    int x=0;
    int *ptr=&x;

    free(ptr); /* Non-compliant: ptr is not dynamically allocated */
   
}

在此示例中,由于函数 free 对不指向动态分配内存的指针进行操作,因此违反了该规则。

#include <stdlib.h>

void func(int arrSize) {
    int *ptr = (int*) malloc(arrSize* sizeof(int));
   
    free(ptr);   /* Block of memory freed once */
    free(ptr);   /* Non-compliant - Block of memory freed twice */
}

在此示例中,当 free 函数在两次操作 ptr 之间未进行重新分配时,就会违反该规则。

检查信息

组:资源
类别:强制
AGC 类别:强制

版本历史记录

在 R2015b 中推出


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.