主要内容

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

MISRA C:2012 Rule 22.1

All resources obtained dynamically by means of Standard Library functions shall be explicitly released

描述

规则定义

All resources obtained dynamically by means of Standard Library functions shall be explicitly released 1 .

理由

资源是您在使用后必须归还给系统的物品。示例包括动态分配的内存和文件描述符。

如果您没有尽快显式释放资源,则可能会因资源耗尽而发生故障。

Polyspace 实现

检查项标记使用:

  • 如果内存未释放,则会调用内存分配函数,如 mallocaligned_alloc

  • 如果文件未关闭,则执行文件打开函数,如 fopen

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

故障排除

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

示例

全部展开

#include<stdlib.h>

void performOperation(int);

int func1(int num)
{
    int* arr1 = (int*) malloc(num * sizeof(int));

    return 0; /* Non-compliant - memory allocated to arr1 is not released */
}

int func2(int num)
{
    int* arr2 = (int*) malloc(num * sizeof(int));

    free(arr2);
    return 0; /* Compliant - memory allocated to arr2 is released */
}

在此示例中,当使用 malloc 函数动态分配的内存未在范围结束之前使用 free 函数释放时,则违反了该规则。

#include <stdio.h>
void func1( void ) {
    FILE *fp1;
    fp1 = fopen ( "data1.txt", "w" );
    fprintf ( fp1, "*" );

    fp1 = fopen ( "data2.txt", "w" );              /* Non-compliant */
    fprintf ( fp1, "!" );
    fclose ( fp1 );
}

void func2( void ) {
    FILE *fp2;
    fp2 = fopen ( "data1.txt", "w" );
    fprintf ( fp2, "*" );
    fclose(fp2);

    fp2 = fopen ( "data2.txt", "w" );              /* Compliant */
    fprintf ( fp2, "!" );
    fclose ( fp2 );
}

在此示例中,文件指针 fp1 指向文件 data1.txt。在 fp1data1.txt 的文件流显式分离之前,它被用于访问另一个文件 data2.txt。因此,第 22.1 条被违反。

func2 中,该规则未被违反,因为文件 data1.txt 已关闭,并且文件指针 fp2 在重用之前已显式地与 data1.txt 脱离。

检查信息

组:资源
类别:必需
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.