NULL can be a valid address
By chys on April 21st, 2010It is only a convention to consider NULL (0) as an invalid pointer. Technically, the operating system or hardware does not really care if a pointer is zero or not, although operating systems may restrict the use of valid null pointers as they may be a security hole.
Consider this program:
#include <stdio.h>
#include <sys/mman.h>
int main ()
{
int *p = mmap (0, 4096, PROT_READ|PROT_WRITE,
MAP_FIXED|MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
*p = 2554;
printf ("p=%p; *p=%d\n", p, *p);
return 0;
}
It attempts to make NULL (0) a valid address and then write to it. On Linux, it runs without error as root, but crashes as a normal user.
Note: Calling mmap with NULL as its first argument usually means the kernel will choose an address. However, if MAP_FIXED is also specified, it instead instructs the kernel to use the very address 0. Only privileged processes are allowed to do so; a non-privileged process only gets EPERM (Permission denied).
This also explains why MAP_FAILED is equal to (void *)-1 instead of NULL.
Related posts:
