0

我分配了 25,000,000,000 个这些单位:

struct test
{
 public:
 test();
 void insert(unsigned int var1, unsigned int var2, unsigned long var3);
      bool isEmpty() const;
      unsigned char * data;
};


test::test()
{
data = NULL;
}

bool test::isEmpty() const
{
  return (data == NULL);
}


unsigned long index = 25000000000;

像这样 :

test *something = new (nothrow) test[index];
    if (!something)
     {
     cout << "Error allocating memory for [something]" << endl;
     return ;
    }
    cout << "DONE !" << endl;

然后我什至将made suredata初始化为NULL。

unsigned long j=0;
        while (j<index) 
        {
          something[j].data = NULL;
          j++;
        }

一切都很好,除非我遍历某事[],如下所示:

test *chk;
unsigned long empty = 0;
unsigned long not_empty = 0;
unsigned long i=0;
for (i=0; i< index; i++ )
{ 
    chk = &something[i];
    if (!chk->isEmpty())
     {
    not_empty++;
    } else
    empty++;
}


cout << "Empty [" << empty << "]" << endl;
cout << "Not Empty [" << not_empty << "]" << endl;
cout << "Total [" << empty + not_empty << "]" << endl;

(最后更新)

原来是硬件问题——内存。有些棍子不能与其他棍子一起正常工作。感谢大家的建议,太糟糕的硬件路径不在答案中o /

(更新)

我得到恒定数量的非 NULL (not_empty) 的初始化元素。仍然不知道为什么。当然,empty + not_empty = index。

如果我data = NULL;在构造函数中注释掉,如果我在分配数组后立即循环遍历数组,我会得到正确的空/非空数字。但是,在强制指针指向 NULL 之后,我得到相同的常量 not_empty 值,在再次循环遍历数组之后。

我还使用 malloc() 将其重新设计为普通指针,它没有任何区别,除了这是我第一次注意到指针是正确的(空的),直到我设置它们。

我用较小的 [index] 值(5,500,000,000)进行了一些测试,但我无法复制该行为。

我使用谷歌的 ltcmalloc 和分配的内存大小建议,它使用正确的 [index] 大小;

4

1 回答 1

0

而不是 25000000000,写 25000000000ul。我怀疑你的数字变成了一个 32 位整数,因此 j < 25000000000 总是正确的,因为 int(25000000000) = -769803776。

于 2013-09-02T14:07:22.127 回答