Memory allocation and NULL pointer

I am confused from something.

first:

int *ptr;
ptr = malloc(10 * sizeof(int));

This type of getting dynamic(heap) memory at run-time, not compile time like arrays.

malloc() may be return NULL if there is no memory.

And NULL is a #define in Standard C Library #define NULL ((void *)0)

So, if the malloc return NULL and it executes at run-time, how the compiler will substitute NULL with void *0 and I know that any text substitution happen in pre-compile phase

Answers


No, you have it wrong. Imagine the malloc function something like this:

void *malloc(size_t n)
{
    /* magic */
    return NULL;
}

The compiler replaces NULL when that translation unit is compiled, i.e. when the standard library is compiled so no trace of NULL survives past the preprocessor phase. After that point, for what it's worth, malloc just returns numbers.


Need Your Help

Query case sensitive in SQL database without setting database to case sensitive

sql database case case-sensitive

I have a column IsSeeded with values 'N' and 'NULL' as one of the possibilities

Iterate through JS object/array, and if you find a match change the value and return the original object/array structure

javascript php jquery arrays

I am trying to get a functionality like PHP in Javascript/Jquery, where we pass the address of a value (&$value) and edit its value in the actual array structure in PHP. For example I have a ob...