ghostbody / 15-cpp-learning

15 c++ learning repository of SDCS SYSU
6 stars 3 forks source link

Memory confusion #12

Open KatharinaLin opened 8 years ago

KatharinaLin commented 8 years ago

I'm struggling to find that some problems on memory error, though I have solved it , but I can not understand why.Can you help me? 16 04 22 2147_1 why I add m_head->prev = NULL;It has no memory problem but it can not run. Another one...

void DouList::operator=(const DouList &src) {
    this->clear();
    if (src.m_head != NULL) {
        DouListNode* m, *p, *r;
        m = src.m_head;
        while (m != NULL) {
            p = new DouListNode(m->elem, NULL, NULL);
            if (m == src.m_head) m_head = p;
            if (m != src.m_head) {
                r->next = p;
                p->prev = r;
            }
            r = p;
            p = p->next;
        }
        m_tail = r;
        p = r = m = NULL;
    }
}

I don't understand why this has no memory problem but can not run.(memory limit exceed 32MB for the two problems above.I'm sure only these two, because I passed after I fixed the the two.

ghostbody commented 8 years ago

@KatharinaLin

  1. What if m_head is NULL and you call m_head->prev = NULL ? Runtime error must be reported.

        while (m != NULL) {
            p = new DouListNode(m->elem, NULL, NULL);
            if (m == src.m_head) m_head = p;
            if (m != src.m_head) {
                r->next = p;
                p->prev = r;
            }
            r = p;
            p = p->next;
        }

You never update m in the loop.........m will never be NULL....

KatharinaLin commented 8 years ago

…a low level bug..I used to use p..this time use m.....My fault.....😭……thanks for answering my foolish question 😭