Home > Back-end >  If you use NULL as parameter of malloc(sizeof()), does it return NULL?
If you use NULL as parameter of malloc(sizeof()), does it return NULL?

Time:12-07

I hope not to sound very foolish here, but does the NULL module actually require memory allocation or not when doing this:

TheNull = malloc(sizeof(NULL));

If true, how can something that has no memory allocated actually exist in the ram?

CodePudding user response:

If you use NULL as parameter of malloc(sizeof()), does it return NULL?

No, unless out-of-memory, like any other allocation.

NULL, the null pointer constant, does not have a particular type. It may be void *, int, long, or some integer type.

Avoid sizeof(NULL) as its size/type may differ from system to system.

CodePudding user response:

The expression is not in any other way related to any NULL module or NULL object. There is are no such things anyway.

NULL is just a useful definition for a null pointer constant.

Depending on the target, NULL is either defined as #define NULL ((void *)0) or #define NULL 0, or possibly some other zero integer constant.

Hence malloc(sizeof(NULL)) either attempts to allocate the number of bytes in an int or in a void pointer.

CodePudding user response:

TheNull = malloc(sizeof(NULL));

That doesn't allocate 0 bytes (because sizeof(NULL) isn't zero), but malloc(0) might. The standard says:

If size is zero, the behavior of malloc is implementation-defined. For example, a null pointer may be returned. Alternatively, a non-null pointer may be returned; but such a pointer should not be dereferenced, and should be passed to free to avoid memory leaks.

So, maybe a null pointer, maybe not.

If true, how can something that has no memory allocated actually exist in the ram?

The pointer returned from malloc might point to a piece of memory slightly larger than what you asked for. For example, if you ask for 1 or 2 bytes, you might get 8 (or even 16) bytes instead. A memory manager often only provides certain size memory blocks (for efficiency), and might require a minimum size so its own bookkeping can fit in a free'd block.

And if it returns an oversized block for 1 or 2 bytes, it could do that for 0 bytes as well.

  • Related