C++:两个动态数组导致内存分配错误

C++: Two dynamic arrays causes memory allocation error

这是我的代码:

int main()
{
    int length = 10;
    int* H = new int(length);
    for(int i=0;i<length;i++)
    {
         H[i] = 0;
    }
    for(int i=0;i<length;i++)
        cout << i << ": " << "\t" << H[i] << "\n";

    double* dos = new double(length);
    for(int i=0;i<length;i++)
    {
        dos[i] = 1.0;
    }
    for(int i=0;i<length;i++)
         cout << i << ": " << dos[i] << "\t" << H[i] << "\n";
    return 0;
}

我正在尝试创建一个全都等于 1.0 的双精度数组和一个全等于 0 的整数数组。当我 运行 这段代码正确输出 dos 数组时,但后来我得到了这个错误

lattice3d: malloc.c:2451: sYSMALLOc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 * (sizeof(size_t))) - 1)) & ~((2 * (sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long)old_end & pagemask) == 0)' failed. Aborted (core dumped)

如果我尝试同时初始化这两个数组,我不会收到内存错误,但数组最终会包含奇怪的值(例如:H 数组看起来像 [0,0, 0,0,0,0,0,0,0,1247506] 或类似的东西)。移动我设置所有 H 和 dos 值的位置,更改不正确的值。

您分配的是 int 而不是数组:

int* H = new int(length);

应该是:

int* H = new int[length];

与您的 double 情况相同:

double* dos = new double(length);

应该是:

double* dos = new double[length];

如果它被分配在堆栈上,你正在做的是 int H(10); 就像 int H = 10;,你的双重情况也是如此; double dos(10) 就像 double dos = 10.

您还泄漏了正在创建的 arrays/values,需要在程序结束时调用 delete[](请注意,这将在您进行上述更正之后):

delete[] H;
delete[] dos;

由于这是标记为 C++ 并且您正在使用 new,值得注意的是,在现代 C++ 中,通常最好尽可能避免使用 new。在这里,使用 std::vector 比动态分配的数组更好。总有比 new 更好的选择,通常涉及使用标准库中的东西。