如果你使用 NULL 作为 malloc(sizeof()) 的参数,它是否 return NULL?

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

我希望在这里不要听起来很愚蠢,但是这样做时 NULL 模块是否真的需要内存分配:

TheNull = malloc(sizeof(NULL));

如果为真,那么没有分配内存的东西怎么会存在于ram中?

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

不,除非像任何其他分配一样内存不足。

NULL空指针常量,没有特定类型。它可能是 void *intlong 或某种整数类型。

避免使用 sizeof(NULL),因为其 size/type 可能因系统而异。

该表达式与任何 NULL 模块NULL 对象 没有任何其他关联。反正没有这些东西。

NULL 只是空指针常量的有用定义。

C 标准以这种方式指定 <stddef.h> 中定义的 NULL 宏和一些其他标准头文件:

7.19 Common definitions <stddef.h>
[...]
The macros are [...]
NULL
which expands to an implementation-defined null pointer constant [...]

空指针常量定义在6.3.2.3:

6.3.2.3 Pointers
[...]
3. An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.67) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.


67) The macro NULL is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.19.

许多目标定义 NULL 被定义为 #define NULL ((void *)0),而其他目标只使用 #define NULL 0,或者可能是其他一些零整数常量表达式(例如:0L0UL...).

因此 malloc(sizeof(NULL)) 尝试分配与 NULL 定义中的表达式类型对应的字节数,可能是 void 指针的大小,但从来没有 0 字节。

是否成功取决于可用内存:

  • 如果成功,return值将是一个有效的指针,不同于NULL

  • 如果malloc(sizeof(NULL));确实returnNULL,这意味着没有可用的内存分配一个非常小的大小,这种情况很严重,应该报告给用户并小心处理。

TheNull = malloc(sizeof(NULL));

这不会分配 0 个字节(因为 sizeof(NULL) 不是零),但是 malloc(0) 可能 。标准说:

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.

所以,可能是空指针,也可能不是。

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

malloc返回的指针可能指向一块比您要求的稍大的内存。例如,如果您请求 1 或 2 个字节,您可能会得到 8(甚至 16)个字节。内存管理器通常只提供特定大小的内存块(为了提高效率),并且可能需要最小大小,以便它自己的 bookkeping 可以放入 free 块中。

如果它 returns 一个 1 或 2 个字节的超大块,它也可以为 0 个字节这样做。