mmap return value during error

2.5k views Asked by At

I could see in the mmap man page the return value during error condition is (void *)-1.

how c compiler will treat (void *) before a constant, here -1.

is the following code snippet is the correct way of checking the error value of mmap?

int *p;
p = (int *)mmap();
if(p == -1)
        printf("error \n");

do we need to use the following error condition check.

if(*p == -1)
        printf("error \n");
1

There are 1 answers

6
Mohit Jain On
int *p = NULL;
void *ret = mmap();
if(ret == MAP_FAILED) {  /* Or if(ret == (void *)-1) */
  /* error */
} else {
  p = ret;
}

Check literally with (void *)-1 or use MAP_FAILED macro which is defined to (void *)-1.

if(*p == -1) is incorrect as you can not dereference the pointer unless you ensure the validity of the pointer. Otherwise the behaviour of the program is undefined.