In C/C++ we’re used to checking for null pointers before dereferencing them, e.g.
int *p = malloc(sizeof(int));
if (p != 0)
{
/* Do something with the pointer */
}
Hence the memory manager can never return a pointer to the first memory address (where p == 0) as the calling program will assume that the memory could not be allocated.
Does that mean that the first byte or word (for alignment purposes) is always unused, both in the entire system memory space and the process’ memory space? Or is this memory used by the system or kernel, which knows which null pointers it can dereference safely?
First of all, to make it clear,
mallocreturning 0 means signaling an error.In most modern operating systems the virtual address space (addresses used in a program) is not the same as the physical address space (the real addresses that the memory understands). Most modern operating systems use paging. So the addresses used in a program (the address returned by
mallocfor example) aren’t the same as the physical ones. The OS has some mechanism to make a correspondence between them.The OS must simply never map anything at the physical address 0 for a regular process and that address will always be invalid if the process tries to access it. The OS itself, for its own benefit can access the memory at address 0 if it so desires.