Freeing memory that is not allocated dynamically can lead to serious errors. The specific consequences of this error depend on the compiler, but they range from nothing to abnormal program termination. Regardless of the compiler, avoid calling free()
on anything other than a pointer returned by a dynamic-memory allocation function, such as malloc()
, calloc()
, or realloc()
.
...
This non-compliant code example sets str
to reference either dynamically allocated memory or a statically allocated string literal depending on the value of argc
. In either case, str
is passed as an argument to free()
. If anything other than dynamic dynamically allocated memory is referenced by str
, the call to free(str)
is erroneous.
...
The Coverity Prevent BAD_FREE checker identifies calls to free()
where the argument is a pointer to a function or an array. Coverity Prevent cannot discover all violations of this rule, so further verification is necessary.
...