Menu

Mismatching Allocation and Deallocation Error When Zero Initializing

2023-05-31
2023-06-01
  • Ayush Gundawar

    Ayush Gundawar - 2023-05-31

    When zero-initializing a dynamically allocated array, Cppcheck incorrectly throws a false positive for a mismatching allocation and deallocation.

    Here is code to reproduce the false positive:

    #include <cstddef>
    #include <iostream>
    
    int main() {
      int length = 125;
      int* array = new int[static_cast<size_t>(length)]{};
      array[0] = 1;
      delete[] array; // Mismatching allocation and deallocation: array
      std::cout << "Success\n";
      return 0;
    }
    

    Cppcheck report:

    src/main.cpp:8:12: error: Mismatching allocation and deallocation: array [mismatchAllocDealloc]
      delete[] array;
               ^
    src/main.cpp:6:16: note: Mismatching allocation and deallocation: array
      int* array = new int[static_cast<size_t>(length)]{};
                   ^
    src/main.cpp:8:12: note: Mismatching allocation and deallocation: array
      delete[] array;
               ^
    

    Odly, Cppcheck does not throw a false positive if not zero-initializing the array or if using uniform initialization when allocating the array.

    Please let me know if any further information is needed, or if I could provide any help of any sort.

     
  • CHR

    CHR - 2023-06-01

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/11743

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.