c - purpose of comparing pointer with (unsigned) -4000L -


in open source component, cjson,

#define is_error(ptr) ((unsigned long)ptr > (unsigned long)-4000l)

above statement used check validity of pointer shown below

json_object* reply = json_object_new_object(); if (!reply || is_error(reply)) {  . . . //error handling } 

how comparing pointer (unsigned long)-4000l validates pointer?

the reason looks they're using pointer value contain "either pointer or error value".

look here:

struct json_object* json_tokener_parse(const char *str) {   struct json_tokener* tok;   struct json_object* obj;    tok = json_tokener_new();   obj = json_tokener_parse_ex(tok, str, -1);   if(tok->err != json_tokener_success)     obj = error_ptr(-tok->err); // <<<<<---   json_tokener_free(tok);   return obj; } 

the function returning special value pointer. err_ptr macro returns negative of error code, presumably because author assumes never valid pointer address.

here test demonstrates expected usage of macro, i.e. malformed json.

 new_obj = json_tokener_parse("{ foo }");   if(is_error(new_obj)) printf("got error expected\n"); 

so, reason using special value can hold "either pointer structure or error code". done union or struct, or other means, chose way.


Comments

Popular posts from this blog

Why can rails not find a route created by a helper? -

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -