1598
This example allocates a BarObj object using the new operator in C++, however, the programmer
then deallocates the object using free(), which may lead to unexpected behavior.
Example Language: C++ (Bad)
void foo(){
BarObj *ptr = new BarObj()
/* do some work with ptr here */
...
free(ptr);
}
Instead, the programmer should have either created the object with one of the malloc family
functions, or else deleted the object with the delete operator.
Example Language: C++ (Good)
void foo(){
BarObj *ptr = new BarObj()
/* do some work with ptr here */
...
delete ptr;
}
Example 2:
In this example, the program does not use matching functions such as malloc/free, new/delete, and
new[]/delete[] to allocate/deallocate the resource.
Example Language: C++ (Bad)
class A {
void foo();
};
void A::foo(){
int *ptr;
ptr = (int*)malloc(sizeof(int));
delete ptr;
}
Example 3:
In this example, the program calls the delete[] function on non-heap memory.
Example Language: C++ (Bad)
class A{
void foo(bool);
};
void A::foo(bool heap) {
int localArray[2] = {
11,22
};
int *p = localArray;
if (heap){
p = new int[2];
}
delete[] p;
}
Affected Resources
• Memory
MemberOf Relationships
CWE Version 4.14
CWE-763: Release of Invalid Pointer or Reference
CWE-763: Release of Invalid Pointer or Reference