简体   繁体   English

C ++将指针与NULL进行比较

[英]C++ comparing a pointer to NULL

I'm fairly new to C++ so bear with me. 我对C ++很新,所以请耐心等待。

I have the following program to learn about dynamic memory allocation. 我有以下程序来了解动态内存分配。

#include<iostream>
#include<new>

using namespace std;

int main ()
{
        int i,n;
        int * p;
        cout << "How many numbers would you like to enter? ";
        cin >> i;

        p = new (nothrow) int [i];

        if (NULL == p){
                cout << "Not enough memory!";
        }else{
                for (n=0; n<i; n++){
                        cout << "Enter a number: ";
                        cin >> p[n];
                }
                cout << "You have entered:  ";
                for(n=0; n<i; n++){
                        cout << p[n] << ", ";
                }
                delete[] p;
        }
        return 0;
}

So long as a sensible amount is entered initially the program runs as expected. 只要最初输入合理的金额,程序就会按预期运行。 But when a huge number (1000000000000) is entered I expected the output "Not enough memory" when in fact it starts printing "Enter a Number: " presumably 1000000000000 times, obviously I haven't waited for output. 但是当输入一个巨大的数字(1000000000000)时,我预计输出“内存不足”,实际上它开始打印“输入一个数字:”大概是100亿次,显然我还没有等待输出。 Since this is in the "else" part of the check, why is this happening? 由于这是检查的“其他”部分,为什么会发生这种情况? I guessed that the comparison isn't working. 我猜这个比较不起作用。 Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

If the first number you enter is more 2^31 one of the possible reasons is the following: 如果您输入的第一个数字更多是2 ^ 31,则可能的原因之一如下:

After you give invalid data the first time cin becomes in invalid state and each next data input operation (eg >> ) does nothing (so it doesn't wait for your input) unless your explicitly return cin to normal state. 在您提供无效数据后,第一次cin变为无效状态,并且每个下一个数据输入操作(例如>>)都不执行任何操作(因此它不会等待您的输入),除非您明确地将cin返回到正常状态。

One of the possible solutions for you are: add after 您可能的解决方案之一是:添加之后

cin >> p[n];

this piece of code: 这段代码:

if (cin.fail()) {
   cout << "Bad data" << endl;
   cin.clear();
}

Depending on the OS, requests for large blocks of memory may be granted even if there is not enough memory, in the hope that by the time it is needed there will be enough (some process might have released memory it held, or more swap memory might become available). 根据操作系统的不同,即使没有足够的内存,也可以授予对大块内存的请求,希望在需要的时候就足够了(某些进程可能释放了它所拥有的内存,或者更多的交换内存)可能会变得可用)。 In those systems the call to the allocator will succeed but memory will be handed to the process only on demand (ie as you use the memory pages) eventually triggering a fault when the next page cannot be allocated. 在这些系统中,对分配器的调用将成功,但内存将仅在需要时(即,当您使用内存页时)传递给进程,最终在无法分配下一页时触发错误。

This is not really an issue with C++, but with the behavior of the operating system. 这不是C ++的问题,而是操作系统的行为。

First, as somebody already noticed, it could be that 1 billion was actually allocated. 首先,正如有人已经注意到的那样,可能实际分配了10亿。 It fits in an integer (limit is ~2 billion), and it requires you to have 4gb of memory. 它适合整数(限制大约20亿),它需要你有4GB的内存。

Anyway, before starting printing, I suggest you print the number you have received in input (and then put a pause, one second, or waiting for an input from the user): that value might be different from what you have expected, because it might be too big to be read correctly from cin. 无论如何,在开始打印之前,我建议您打印输入中收到的数字(然后暂停,一秒钟或等待用户输入):该值可能与您预期的不同,因为它可能太大了,无法从cin中正确阅读。

You might therefore want to define i as an unsigned long long . 因此,您可能希望将i定义为unsigned long long

What is the difference between unsigned long and unsigned long long? unsigned long和unsigned long long有什么区别?

Also, check you are not putting cin in an error state giving a string it cannot parse 另外,检查你是不是将cin置于错误状态,给出了一个无法解析的字符串

Edit from Mooing Duck suggestion: Mooing Duck建议编辑:

Use 使用

 if (std::cin >> variable) { }

or 要么

 while(std::cin >> variable) { }

to avoid this problem. 避免这个问题。 Avoid checking .bad() , .fail() , or .eof() , they're often misused, leading to bugs. 避免检查.bad() .fail().eof() ,它们经常被误用,导致错误。

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

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