IssueInvalid free of pointer occurs
when a block of memory released using the free function
was not previously allocated using malloc, calloc,
or realloc.
RiskThe free function releases a block of memory allocated on the
heap. If you try to access a location on the heap that you did not allocate
previously, a segmentation fault can occur.
The issue can highlight coding errors. For instance, you perhaps wanted to use the
free function or a previous malloc
function on a different pointer.
FixIn most cases, you can fix the issue by removing the free
statement. If the pointer is not allocated memory from the heap with
malloc or calloc, you do not need to free
the pointer. You can simply reuse the pointer as required.
If the issue highlights a coding error such as use of free or
malloc on the wrong pointer, correct the error.
If the issue occurs because you use the free function to free
memory allocated with the new operator, replace the
free function with the delete
operator.
Example - Invalid Free of Pointer Error#include <stdlib.h>
void Assign_Ones(void)
{
int p[10];
for(int i=0;i<10;i++)
*(p+i)=1;
free(p);
/* Defect: p does not point to dynamically allocated memory */
}
The pointer p is deallocated
using the free function. However, p points
to a memory location that was not dynamically allocated.
Correction — Remove Pointer Deallocation
If the number of elements of the array p is
known at compile time, one possible correction is to remove the deallocation
of the pointer p.
#include <stdlib.h>
void Assign_Ones(void)
{
int p[10];
for(int i=0;i<10;i++)
*(p+i)=1;
/* Fix: Remove deallocation of p */
} Correction — Introduce Pointer Allocation
If the number of elements of the array p is
not known at compile time, one possible correction is to dynamically
allocate memory to the array p.
#include <stdlib.h>
void Assign_Ones(int num)
{
int *p;
/* Fix: Allocate memory dynamically to p */
p=(int*) calloc(10,sizeof(int));
for(int i=0;i<10;i++)
*(p+i)=1;
free(p);
}