Redundant Free Usage High

The product calls free method twice on the same memory address, which leads to modification of unexpected memory locations.

Detector ID
c/redundant-free-usage@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1#include <stdlib.h>
2#include <string.h>
3
4int redundantFreeUsageNonCompliant(char *argv[]) {
5    char *buf1;
6    char *buf2;
7    buf1 = (char *) malloc(sizeof(char) * 10);
8    free(buf1);
9    buf2 = (char *) malloc(sizeof(char) * 5);
10    strncpy(buf2, argv[1], 1);
11    // Noncompliant: Redundent use of `free` on buf1 without memory reallocation
12    free(buf1);
13    free(buf2);
14}

Compliant example

1#include <stdlib.h>
2#include <string.h>
3
4int redundantFreeUsageCompliant() {
5    char *var = malloc(sizeof(char) * 10);
6    free(var);
7    var = malloc(sizeof(char) * 10);
8    // Compliant: Use of free on variable after memory reallocation
9    free(var);
10    return 0;
11}