Monday, October 28, 2019

How to use IS_ERR and PTR_ERR? What do they mean?

From the kernel definition there are three macros:
  1. IS_ERR - used to check, Returns non-0 value if the ptr is an error. Otherwise 0 if it’s not an error.
  2. PTR_ERR - used to print. Current value of the pointer.
  3. IS_ERR_VALUE - is explained a little bit more detail here1.
I find this the most useful for kernel space programming. Used as follows- if ptr is the pointer you want to check then use it as follows:
if (IS_ERR(ptr))
     printk("Error here: %ld", PTR_ERR(ptr));
Their code definitions are as follows in the kernel:
#define IS_ERR_VALUE(x) unlikely((x) >= (unsigned long)-MAX_ERRNO)

static inline void * __must_check ERR_PTR(long error)
    return (void *) error;

static inline long __must_check PTR_ERR(const void *ptr)
    return (long) ptr;

static inline long __must_check IS_ERR(const void *ptr)
    return IS_ERR_VALUE((unsigned long)ptr);

static inline long __must_check IS_ERR_OR_NULL(const void *ptr)
    return !ptr || IS_ERR_VALUE((unsigned long)ptr);


  1. Definition and use of IS_ERR_VALUE↩︎