Reputation: 1696
I searched C standard for that, but I didn't find anything about that question. If that's implementation-defined, why is it always safe to use malloc like this?
char *p = (char*) malloc(100);
if (p == NULL)
return;
for (i=0; i<100; i++)
{
p[i] = ........
}
Upvotes: 0
Views: 85
Reputation: 667
malloc returns NULL if it couldn't allocate the memory. That's why you can test like that.
NULL is defined in the standard as a null pointer, and is guaranteed to compare unequal to a pointer to any object or function. It's an address for something that can never be a memory location.
A pointer just points at a memory location. In C, when you allocate memory, the first byte of that memory is always what's going to be pointed to. Knowing where the memory starts, and the size, you can know where it ends.
But a pointer can point to anywhere in that array. You can set a char * p_pointer = p + 1 or the equivalent &p[1]; p_pointer[-1] points to p[0].
Upvotes: 1