c++程序出现exit code -1073740940 (0xC0000374)
PHPz
PHPz 2017-04-17 15:02:18
0
2
1554

一道动态规划的算法题.
dp是我用new关键字分配的一个整形数组用来记录转移量,在程序51行使用"delete []dp;"去释放内存
出现exit code -1073740940 (0xC0000374)的错误,用的是gnu++11

#include <iostream>
#include <vector>

using namespace std;

vector<int> get_pisor(int num)
{
    vector<int> vec;
    for (int i = 2; i < num; ++i) {
        if (num % i == 0) {
            vec.push_back(i);
        }
    }
    return vec;
}

int max_step(int v_start, int v_end)
{
    if (v_start >= v_end) {
        return -1;
    }
    int start = v_start;
    int end = v_end;
    int rslt;
    int *dp = new int[end - start + 1];
    //初始化所有dp内的元素
    for (int i = start; i <= end; ++i) {
        dp[i] = 0;
    }
    vector<int> vec;
    for (int i = start; i <= end; ++i) {
        vec = get_pisor(i);
        //如果向量为空,说明在该步不存在约数,无法到达end
        if (vec.empty()) {
            dp[i] = 0;
        } else {
            vector<int>::iterator iter;
            for (iter = vec.begin(); iter != vec.end(); ++iter) {
                if (dp[i + (*iter)] == 0) {
                    dp[i + (*iter)] = dp[i] + 1;
                } else {
                    dp[i + (*iter)] = (dp[i] + 1) > dp[i + (*iter)] ? dp[i + (*iter)] : dp[i] + 1;
                }
            }
            vec.clear();
        }
    }

    rslt = dp[v_end];

    delete []dp;
    return rslt;
}

int main()
{
    int rslt = max_step(4, 24);
    cout<<rslt<<endl;
}

按理说我动态申请的数组在使用最后delete应该是没问题的吧,但不知道为什么会出现这个错误,还请指教

PHPz
PHPz

学习是最好的投资!

reply all(2)
巴扎黑

I seem to have seen an error in array initialization. As shown below, solve this problem first. Let’s talk about other things.

Peter_Zhu

The reason lies in dp[i + (*iter)]. The maximum array index here will definitely exceed end. Using 2 times the end can solve this problem.
The number released by delete should be the number released by new. The remaining ones have not been released cleanly, so the program will be cored

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template