c语言中malloc的返回值,c语言里malloc返回NULL是什么意思?

时间:2025-04-20 13:53:53

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.

malloc 返回一个指向已分配空间的 void 指针,如果内存不足,则返回 NULL。若要返回指向非 void 类型的指针,请在返回值上使用类型转换。由返回值指向的存储空间保证适当地对齐以存储任何类型的对象。如果 size 是 0,malloc 会在堆中分配一个零长度的项目,并返回一个指向该项目的有效指针。即使请求的内存量很小,也要始终检查 malloc 的返回值。