CERT-MEM34-C_c
In this section:
Synopsis
Only free memory allocated dynamically.
Enabled by default
Yes
Severity/Certainty
High/High

Full description
Freeing memory that is not allocated dynamically can result in heap corruption and other serious errors.
Coding standards
- CERT MEM34-C
Only free memory allocated dynamically
- CWE 590
Free of Memory not on the Heap
Code examples
The following code example fails the check and will give a warning:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
enum { MAX_ALLOCATION = 1000 };
int main(int argc, const char *argv[]) {
char *c_str = NULL;
size_t len;
if (argc == 2) {
len = strlen(argv[1]) + 1;
if (len > MAX_ALLOCATION) {
/* Handle error */
}
c_str = (char *)malloc(len);
if (c_str == NULL) {
/* Handle error */
}
strcpy(c_str, argv[1]);
} else {
c_str = "usage: $>a.exe [string]";
printf("%s\n", c_str);
}
free(c_str);
return 0;
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
enum { MAX_ALLOCATION = 1000 };
int main(int argc, const char *argv[]) {
char *c_str = NULL;
size_t len;
if (argc == 2) {
len = strlen(argv[1]) + 1;
if (len > MAX_ALLOCATION) {
/* Handle error */
}
c_str = (char *)malloc(len);
if (c_str == NULL) {
/* Handle error */
}
strcpy(c_str, argv[1]);
} else {
printf("%s\n", "usage: $>a.exe [string]");
return EXIT_FAILURE;
}
free(c_str);
return 0;
}