gkaykck
gkaykck

Reputation: 2367

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);

Upvotes: 0

Views: 1164

Answers (5)

Dimitar
Dimitar

Reputation: 4783

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); \
        } \
    } \

Upvotes: 0

Gabriel
Gabriel

Reputation: 11

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

Upvotes: 1

jim mcnamara
jim mcnamara

Reputation: 16379

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.

Upvotes: 3

qrdl
qrdl

Reputation: 34958

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.

Upvotes: 0

Uri
Uri

Reputation: 89729

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.

Upvotes: 6

Related Questions