c语言里malloc返回NULL是什么意思?

在读一本数据结构的书 经常出现类似
int *a;
if((a=malloc(size))==NULL)
xxx...

这是什么意思?

阅读 7.3k
2 个回答
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 的返回值。

在动态分配内存是的时候失败了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进