开发者

Is a pointer assigned or not in C?

How can I write an if statement which tells the progra开发者_C百科m if the pointer is assigned or not?

WRONG example

if (*badpdr[0]==0);


You mean if (badptr==NULL) ?

Note that you have to initially set your pointer to NULL when you define it or when you "unassign it" (e.g., you delete the object it refers to). Otherwise, it will contain junk and this test would fail because the value would not be a 0.

You can also do the comparison to 0 instead of NULL, there's already enough arguments on SO which is the correct form so I won't repeat them.


char *ptr=NULL;

initalize the pointer to NULL; then later on you can check if it is NULL to see if it is valid before you try to deference it.


In C++ when int variables are not assigned they have the intial value of 2686392!


You can install signal handler for SIGSEGV and then try to dereference the pointer - if you find yourself inside signal handler, pointer wasn't assigned (or points to invalid memory address, which basically is the same thing)

However there could be the situations when unassigned pointer points to valid address that belongs to process memory space - in this case there will be no SIGSEGV raised.


You can use a macro, which does the job:

#define NP_CHECK(ptr) \
    { \
        if (ptr == NULL) { \
            fprintf(stderr, "%s:%d NULL POINTER: %s\n", \
                __FILE__, __LINE__, #ptr); \
            exit(-1); \
        } \
    } \
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜