cvisual-studio-2022compiler-warningsstatic-analysis

How to suppress this false positive warning from Clang static code analyzer?


#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int a;
} tempStruct1;

typedef struct {
    int b;
} tempStruct2;

typedef struct {
    tempStruct1 *temp1;
    tempStruct2 *temp2;
} structA;

typedef struct {
    int c;
} structB;

typedef struct {
    int d;
} structC;

void do_something(structA* base)
{
    int total_size = sizeof(structB) + sizeof(structC) + sizeof(tempStruct1) + sizeof(tempStruct2);
    base->temp1 = malloc(total_size);

    if (base->temp1)

    {
        structB* ptr1 = (structB*)(base->temp1 + 1);
        structC* ptr2 = (structC*)(ptr1 + 1);
        base->temp2 = (tempStruct2*)(ptr2 + 1);   //warning : Potential memory leak [unix.Malloc]
    }

    free(base->temp1);
}

void fun()
{
    structA base;
    do_something(&base);
}

int main()
{
    fun();
    return 0;
}

My use-case is almost similar to the code mentioned above. I'm getting this memory leak warning for legacy Clang based static analyzer. Because it is assuming base pointer is being over written. //NOLINT doesn't seem to work for my case.

Command I'm using to run the analyzer:

"clang.exe" --analyze -fno-strict-aliasing -fno-common -g -Wall -std=gnu17 -O0 -fomit-frame-pointer -RTCs -ffunction-sections -fxray-instrument -DNDEBUG -DALTERNATE_PCI_SWITCHING_TEST_OFF temp.c

I tried to suppress the warning and modified it like this:


//..
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wcast-align"
base->temp2 = (tempStruct2*)(ptr2 + 1);
#pragma clang diagnostic pop

It doesn't seem to work.
I'm certain it is false positive. Is there any way to resolve this warning without changing the logic. Appreciate it.


Solution

  • #ifndef __clang_analyzer__
    base->temp2 = (tempStruct2*)(ptr2 + 1); 
    #endif
    

    Seems to work for this case, basically making the code dead to the analyzer.
    Referred from this documentation