[ACCEPTED]-Pointer pointing to an empty array-pointers

Accepted answer
Score: 11

*array == NULL is wrong. You are dereferencing the pointer 14 first (which could lead to a segfault if 13 the pointer really is null) and then comparing 12 its int value to a pointer value. Moreover, your 11 compiler will perfectly accept that erroneous 10 expression if NULL is defined as just 0 and not 9 (void *) 0.

You should be checking array == NULL to see if the passed 8 pointer refers to anything, and then dereference 7 it only in case it's not NULL.

Be aware, however, that 6 dereferencing a non-null pointer isn't guaranteed 5 to be a safe operation either. If the pointer 4 contains a garbage value because it was 3 allocated on the stack and not initialized, or 2 if it refers to a deallocated region of 1 memory, nasty bugs can happen.

Score: 5

You want if (array == NULL) -- but unless you first initialize 5 array to NULL, it won't do any good either. I think 4 you'd be better off backing up and telling 3 us a bit more about what you're trying to 2 accomplish, and trying to get help trying 1 to accomplish your overall goal.

Score: 1

The only safe way to determine the allocation 1 status of *array is to:

  1. Make sure *array is set to NULL is not allocated. int *array = NULL;
  2. Check if the array is NULL: if (array == NULL) return -1;
Score: 1

You can't reliably check if some memory 17 location is allocated. *array is not a valid code, because 16 it's the same as array[0], but array[0] is not allocated. Non-allocated 15 memory location can contain any value.

The only 14 option is to ensure that you get the information 13 whether the array is allocated alongside 12 with your array. A popular option is representing 11 unallocated array as NULL, but you may choose 10 other option as well.

By the way, there is 9 a difference between an empty array (that 8 is, array of size 0), and array which is 7 not allocated at all. The first option occurs 6 when you use malloc(0), the second when your pointer 5 is not initialized at all. For malloc(0) it's allowed 4 to return NULL, but it's allowed to return a 3 non-NULL pointer (which you however can't 2 dereference) as well. Both ways are valid 1 according to the standard.

Score: 1

The immediate problem with your code is 11 that you dereferencing array before comparing 10 it to NULL. The type of the expression *array is int, not 9 int *. Leave off the dereference operator and 8 the types will match:

if (array == NULL) {...}

Note that an uninitialized 7 pointer is only guaranteed to contain NULL 6 if it was declared with static extent (i.e. it 5 was either declared at file scope or with 4 the static keyword in front of it). Similarly, calling 3 free on a pointer won't set that pointer value 2 to NULL; it will contain the same pointer 1 value as before, but it will now be invalid.

Score: 0

You must use it like this:

if(array == NULL) ...


More Related questions