メインコンテンツ

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

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

根拠

メモリを割り当てる標準ライブラリ関数は malloccalloc および realloc です。

メモリのブロックは、そのアドレスが関数 free または realloc に渡されると解放されます。次のようにすると、動作は未定義になります。

  • 割り当てられていないメモリのブロックを解放する。

  • 既に解放済みのメモリのブロックを解放する。

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

この例では、関数 freeptr に対し 2 回実行され、その間に再割り当てがない場合に、ルールに違反しています。

チェック情報

グループ: Resources
カテゴリ: Mandatory
AGC カテゴリ: Mandatory

バージョン履歴

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.