使用新分配内存时,是否需要检查空? [英] Do I Need To Check For Null When Allocating The Memory Using New?

查看:88
本文介绍了使用新分配内存时,是否需要检查空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



请为此建议答案。在我的代码中,我分配内存如下所示。

Hi all,

Please suggest the answer for this. In my code I am allocating the memory like as below.

voice_buffer = new char[no_of_bytes + 20];
input_file->ReadData(voice_buffer,no_of_bytes);



这里我需要检查NULL条件还是需要添加此代码来尝试catch块?


Here do I need to check for the NULL conditions or is it required to add this code in to try catch block?

推荐答案

简答:

看看:我需要在p = new Fred()之后检查null吗?



Short answer: no.
Take a look: Do I need to check for null after p = new Fred()?:

在C ++中,如果运行时系统在p = new Fred()期间无法分配sizeof(Fred)字节的内存,则会抛出std :: bad_alloc异常。 与malloc()不同,new永远不会返回null!



因此你应该简单地写一下:



Fred * p = new Fred(); //无需检查p是否为空

In C++, if the runtime system cannot allocate sizeof(Fred) bytes of memory during p = new Fred(), a std::bad_alloc exception will be thrown. Unlike malloc(), new never returns null!

Therefore you should simply write:

Fred * p = new Fred(); // No need to check if p is null


这篇关于使用新分配内存时,是否需要检查空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆