0

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?

Mathue24
  • 152
  • 1
  • 2
  • 8
  • If you get to line 40, `encrypted` is definitely null, and `printf("Encrypted:%s\n", encrypted)` is undefined behavior. – aschepler Apr 06 '17 at 20:16

1 Answers1

2

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");} 
dbush
  • 205,898
  • 23
  • 218
  • 273
  • @Mathue24: notice that it's just a courtesy that glibc makes you to print `(null)` if you pass a NULL string - it's not mandated by the standard, and gcc itself routinely rewrites `printf` calls to `puts` calls, where it straight crashes if NULL is passed. If you need to add a debug print to see if the string is not NULL do it explicitly as shown above. – Matteo Italia Apr 06 '17 at 21:14