C++:检查动态取消分配是否正常工作

C++: Checking if dynamic de-allocation has worked correctly

我目前正在关注 Springer 的一本名为 "Guide to scientific computing in C++" 的书,其中一个关于指针的练习如下:

"Write code that allocates memory dynamically to two vectors of doubles of length 3, assigns values to each of the entries, and then de-allocates the memory. Extend this code so that it calculates the scalar product of these vectors and prints it to screen before the memory is de-allocated. Put the allocation of memory, calculation and de-allocation of memory inside a for loop that runs 1,000,000,000 times: if the memory is not de-allocated properly your code will use all available resources and your computer may struggle."

我的尝试是:

for (long int j = 0; j < 1000000000; j++) { 

    // Allocate memory for the variables
    int length = 3;
    double *pVector1;
    double *pVector2;
    double *scalarProduct;
    pVector1 = new double[length];
    pVector2 = new double[length];
    scalarProduct = new double[length];

    for (i = 0; i < length; i++) { // loop to give values to the variables
        pVector1[i] = (double) i + 1;
        pVector2[i] = pVector1[i] - 1;
        scalarProduct[i] = pVector1[i] * pVector2[i];
        std::cout << scalarProduct[i] << " " << std::flush; // print scalar product
    }
    std::cout << std::endl;

    // deallocate memory
    delete[] pVector1;
    delete[] pVector2;
    delete[] scalarProduct;
}

我的问题是此代码可以运行,但效率低下。似乎内存的取消分配应该快得多,因为它在终止之前运行了超过一分钟。我假设我滥用了取消分配,但还没有找到修复它的正确方法。

您的代码完全按照预期的方式工作,运行 很长一段时间没有因 out_of_memory 而导致计算机崩溃。这本书可能有点过时,因为它假设您在崩溃前不能分配超过 72.000.000.000 字节。您可以测试它是否删除删除,从而泄漏内存。