C & C++

C & C++

Made by DeepSource

Potential heap memory use after free CXX-S1012

Security
Major
cwe-416

When a program requests memory from the heap, it is given a pointer to the starting address of that memory block. When the program frees that memory block, the memory is returned to the heap and the pointer is no longer valid.

Using freed heap memory can result in undefined behavior and potentially cause serious problems in a program.

If the program tries to access the memory through that pointer after it has been freed, it can lead to several issues such as:

  • Segmentation faults or access violations: Attempting to read or write to a memory address that has been freed can cause the program to crash or terminate unexpectedly.
  • Data corruption: Accessing freed memory can overwrite data in other parts of the program, leading to unpredictable behavior or data corruption.
  • Security vulnerabilities: If an attacker can control the contents of freed memory, they may be able to execute malicious code or gain access to sensitive information.

To avoid these issues, it's important for developers to properly manage memory in their programs by deallocating memory only when it's no longer needed and avoiding accessing freed memory.

Bad practice

int* mem = (int*)malloc(sizeof(int));
*mem = 10;
if (rand() % 10 == 0) {
    free(mem);
}
printf("%d", *mem); // possible use after the pointer has been freed

References