C ++动态内存分配VS自动内存分配

时间:2018-03-03 11:41:08

标签: c++ out-of-memory

相当奇怪的是,我构建了一个搜索树并进行搜索。在搜索功能中,如果我动态分配内存并删除,内存限制将超过(我在OJ中解决问题)。但是,如果我只声明一个普通变量,就没有内存不足的问题。代码如下所示:(我递归搜索树(类似于2DTree))

void Search(int x1, int x2, int y1, int y2, node* n, int* st, long long* tem)    {
    int nx, ny, nx1, nx2, ny1, ny2;
    nx = n->x; ny = n->y;
    nx1 = n->x1; nx2 = n->x2;
    ny1 = n->y1; ny2 = n->y2;
    node* l = n->lc;
    node* r = n->rc;
    if (x1 > nx2 || x2<nx1 || y1>ny2 || y2 < ny1) { 
        *st = 0;
        *tem = 0;
        return;
    }
    else if (x1 <= nx1 && x2 >= nx2 && y1 <= ny1 && y2 >= ny2) { 
        *st = n->childNum;
        *tem = n->tSum;
        return;
    }
    else {  
        //part with memory issue
        long long* tl = new long long;
        int* sl = new int;
        *tl = 0;  *sl = 0;
        if (l) Search(x1, x2, y1, y2, l, sl, tl);
        *st += (*sl );
        *tem += (*tl);
        delete tl, sl;
        long long* tr = new long long;
        int* sr = new int;
        if (r) Search(x1, x2, y1, y2, r, sr, tr);
        *st += (*sr);
        *tem += (*tr);
        delete tr, sr;
        if (nx >= x1 && nx <= x2 && ny >= y1 && ny <= y2) { 
            *st += 1;
            *tem += n->t;
        }

        //this goes OK
        long long tl = 0;
        int sl = 0;
        if (l) Search(x1, x2, y1, y2, l, &sl, &tl);
        *st += (sl);
        *tem += (tl);
        long long tr = 0;
        int sr = 0;
        if (r) Search(x1, x2, y1, y2, r, &sr, &tr);
        *st += (sr);
        *tem += (tr);
        if (nx >= x1 && nx <= x2 && ny >= y1 && ny <= y2) { 
            *st += 1;
            *tem += n->t;
        }
    }
    return;
}

1 个答案:

答案 0 :(得分:2)

感谢@nwp,我意识到这是一个微不足道的问题。

原始代码不起作用的原因是delete的优先级高于逗号,因此delete a, b, c;(delete a), b, c相同,因此,

delete a,b,c;仅删除a。

同样,cin >> a,b;cin >> a;

相同

检查this