Search code examples
cif-statementpointersnullpointerexceptiondeclaration

Check for NULL pointer doesn't work for char pointer


I know it must be silly to ask about, but my if statement that checks for null pointer doesn't seem to work. The code continues, and once I dereference the pointer, an error occurs. The code is kernel code, if that matters.

// issue.h
static char *sys_efile[FILE_PATH_SIZE]; // 100

// issue_main.c
#include "issue.h"

if (sys_efile == NULL)
    return -EFAULT;

file = filp_open(*sys_efile, O_RDWR, 0);
BUG: kernel NULL pointer dereference, address: 0000000000000000
[   32.262950] #PF: supervisor read access in kernel mode
[   32.262952] #PF: error_code(0x0000) - not-present page

Do I miss smth?


Solution

  • You declared an array of pointers with static storage duration.

    static char *sys_efile[FILE_PATH_SIZE];
    

    So all elements of the array are implicitly initialized as null-pointers. But the array itself can not be implicitly converted to a null pointer because it occupies memory. So this statement

    if (sys_efile == NULL)
    

    will always evaluate to false.

    Either actually instead of the array of pointers you want to declare a character array like

    static char sys_efile[FILE_PATH_SIZE]; // 100
    

    and then you may write for example

    // issue_main.c
    #include "issue.h"
    
    if ( *sys_efile == '\0' )
        return -EFAULT;
    
    file = filp_open( sys_efile, O_RDWR, 0);
    

    Or if you are going to use an array of pointers then the if statement should look like

    static char *sys_efile[FILE_PATH_SIZE]; // 100
    
    // issue_main.c
    #include "issue.h"
    
    if ( *sys_efile == NULL)
        return -EFAULT;
    
    file = filp_open(*sys_efile, O_RDWR, 0);