简体   繁体   中英

Is a pointer assigned or not in C?

How can I write an if statement which tells the program 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" (eg, 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.

C++当未分配int变量时,它们的初始值为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); \
        } \
    } \

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM