C and C++


BADFUNC.STDLIB_H_MEM : Use of <stdlib.h> Allocator/Deallocator

Summary

A use of one of the following, declared in <stdlib.h> (C) / <cstdlib> (C++), when defined as a function: malloc(), calloc(), realloc(), free().

These functions are disallowed by some coding standards.

If your libc implementation defines these as macros, uses will instead be reported as Use of <stdlib.h> Allocator/Deallocator Macro warnings.

Properties

Class Name Use of <stdlib.h> Allocator/Deallocator
Significance style
Mnemonic BADFUNC.STDLIB_H_MEM
Categories
MisraC2023 MisraC2023:21.3 The memory allocation and deallocation functions of <stdlib.h> shall not be used
Misra2012 Misra2012:21.3 The memory allocation and deallocation functions of <stdlib.h> shall not be used
Misra2004 Misra2004:20.4 Dynamic heap memory allocation shall not be used
AUTOSARC++14 AUTOSARC++14:A18-5-1 Functions malloc, calloc, realloc and free shall not be used.
MisraC++2008 MisraC++2008:18-4-1 Dynamic heap memory allocation shall not be used.
MisraC++2023 MisraC++2023:21.6.1 Dynamic memory shall not be used
  MisraC++2023:21.6.2 Dynamic memory shall be managed automatically
CWE CWE:710 Improper Adherence to Coding Standards
POW10 POW10:3 Do not use dynamic memory allocation after initialization.
JPL JPL:5 Do not use dynamic memory allocation after task initialization.
Availability Available for C and C++.
Enabling Checks for this warning class are disabled by default. To enable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += allow class="Use of <stdlib.h> Allocator/Deallocator"

Example

#include <cstdlib>
#include <iostream>

class Intpair {
  public:
    int a;
    int b;
    Intpair(int aval, int bval): a(aval),b(bval){}
    int sum(){return a+b;}
};

int baduse(){
    int s;
    Intpair *i = (Intpair*)malloc(sizeof(Intpair));   // Warning issued here:
                      // - 'Use of <stdlib.h> Allocator/Deallocator' if malloc() implemented as a function
                      // - Use of <stdlib.h> Allocator/Deallocator Macro if malloc() implemented as a macro 
    if (i==NULL) {return 0;}
    i->a = 5;
    i->b = 7;
    s = i->sum();
    free(i);          // Warning issued here:
                      // - 'Use of <stdlib.h> Allocator/Deallocator' if free() implemented as a function
                      // - Use of <stdlib.h> Allocator/Deallocator Macro if free() implemented as a macro 
    return s;
}

int gooduse(){                              // OK: uses constructor and destructor instead of malloc/free. 
    Intpair *i = new Intpair(5,7);                   
    int s =  i->sum();
    delete i;
    return s;
}

Relevant Configuration File Parameters

This class is implemented using a BAD_FUNCTION_* rule set in the general template configuration file.

The following configuration file parameters affect checks for this warning class.