简体   繁体   English

如果 malloc 返回 NULL 怎么办?

[英]What to do if malloc returns NULL?

in my program I work with big amount of data.在我的程序中,我处理大量数据。 I use the malloc() function to allocate memory for my large array.我使用 malloc() 函数为我的大数组分配内存。 After I allocate the memory, I check if the pointer is NULL (that's because there isn't that big memory space or I don't know why).分配内存后,我检查指针是否为NULL(这是因为没有那么大的内存空间或者我不知道为什么)。

But sometimes my pointer is NULL.但有时我的指针是NULL。 So now what to do?那么现在该怎么办? I made a loop, that tries to allocate it again and again if the pointer is NULL.我做了一个循环,如果指针为NULL,它会尝试一次又一次地分配它。 But it becomes to an infinite loop and it still says, that the pointer is NULL.但它变成了一个无限循环,它仍然说,指针为 NULL。 So how to allocate the memory if it doesn't want to?那么如果不想分配内存怎么分配呢?

Thank you for your responses.谢谢你的回复。

It depends on the criticality of the memory you try to allocate:这取决于您尝试分配的内存的重要性:

  • if the program can't run without it, just log the error and shutdown;如果程序没有它就无法运行,只需记录错误并关闭;
  • if the program can run without it, and if it makes sense to run in degraded mode, log the error, drop the treatment and continue hoping for the best.如果程序可以在没有它的情况下运行,并且在降级模式下运行有意义,请记录错误,放弃处理并继续希望最好。

If malloc fails then you have run out of available memory.如果malloc失败,那么您的可用内存已用完。 There is no point in calling it again with the same requested size.用相同的请求大小再次调用它是没有意义的。 It will continue to fail until you release some of your allocated memory using free .它会继续失败,直到您使用free释放一些分配的内存。

If you are working on an embedded system that has limited memory, good chances are that the malloc() returned a NULL because you were attempting to request more memory than it had free (in one contiguous block).如果您正在使用内存有限的嵌入式系统,则 malloc() 很有可能返回 NULL,因为您试图请求比空闲内存更多的内存(在一个连续块中)。 Without knowing more implementation details, or the size of malloc() request, I cannot speculate about why this was.在不知道更多实现细节或 malloc() 请求的大小的情况下,我无法推测这是为什么。

However, it does point to the fact that you have to understand the memory utilization of your solution, so that you can determine what memory is being used where, and determine how you can free memory that might be in use, or if you have to move to a system design with more system memory.但是,它确实表明您必须了解解决方案的内存利用率,以便您可以确定在何处使用了哪些内存,并确定如何释放可能正在使用的内存,或者是否必须转向具有更多系统内存的系统设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM