Mathue24
Mathue24

Reputation: 178

C: Cppcheck : Possible null point dereference

So here in main.c, ive got this part of code that prints the content of encrypted if its not empty. Its really simple as that.

The cpp error is:

[main.c:40]: (error) Possible null pointer dereference: encrypted - otherwise it is redundant to check if encrypted is null at line 31

The code:

char* encrypted = bmp_encrypt(key, text);
    if(encrypted != NULL) //error points here (line 31)
    {
        printf("Encrypted:");
        for(int i=0; i<strlen(text);i++)
        {
            printf("%x ", (unsigned char) encrypted[i]);
        }
        printf("\n");
    }
    else{printf("Encrypted:%s\n", encrypted);} //this is line 40

Thing is, its working as intended but cppcheck keeps bugging me, should I fix it? is it wrong to do this?

Upvotes: 0

Views: 667

Answers (1)

dbush
dbush

Reputation: 223972

The else block of your code will only be entered if encrypted is NULL. So you're passing a NULL pointer to printf. That can invoke undefined behavior.

Since you know the pointer is NULL at that point, just explicitly print that it is NULL:

else{printf("Encrypted: (null)\n");} 

Upvotes: 2

Related Questions