...
Freeing memory that is not allocated dynamically can lead to serious errors similar to those discussed in MEM31-C. Free dynamically allocated memory exactly once. The consequences of this error depend on the implementation, but they range from nothing to abnormal program termination. Regardless of the implementation, avoid calling free()
on anything other than a pointer returned by a dynamic memory allocation function, such as malloc()
, calloc()
, realloc()
, or aligned_alloc()
.
A similar situation arises when realloc()
is supplied a pointer to nondynamically allocated memory. The realloc()
function is used to resize a block of dynamic memory. If realloc()
is supplied a pointer to memory not allocated by a memory allocation function, such as malloc()
, the program may terminate abnormally.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdlib.h>
enum { BUFSIZE = 256 };
void f(void) {
char buf[BUFSIZE];
char *p = (char *)realloc(buf, 2 * BUFSIZE); /* violation */
}
|
Compliant Solution(realloc()
)
...