c++ [已关闭] 2013年第一季度总结

svdrlsy4  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(65)

**已关闭。**此问题需要debugging details。目前不接受回答。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将帮助其他人回答问题。
8天前关闭。
Improve this question
为什么会出现这样的错误:

int main(){
    lista *head, *x;
    head = nullptr;
    const int len = 3;
    int y[len] = {13, 4, 32};
    for(int i = len - 1; i >= 0; i--){
        x = new lista;
        x -> val = y[i];
        x -> next = head;
        head = x;
    }
    lista *p = head;
    // Changing lines are the next ones
    while(p->next != nullptr){
        p = p->next;
    }
    delete p;
    p = nullptr;

    print_lista(head);
    return 0;
}

字符串
但这不是:

int main(){
    lista *head, *x;
    head = nullptr;
    const int len = 3;
    int y[len] = {13, 4, 32};
    for(int i = len - 1; i >= 0; i--){
        x = new lista;
        x -> val = y[i];
        x -> next = head;
        head = x;
    }
    lista *p = head;
    // Changing lines are the next ones
    while(p->next->next != nullptr){
        p = p->next;
    }
    delete p->next ;
    p->next = nullptr;

    print_lista(head);
    return 0;
}


也不是这样的

while(p->next != nullptr){
    p = p->next;
}
p = p->next;
delete p;
p = nullptr;


这是给定的错误:
被监视的命令转储核心
Segmentation fault
这不是一回事吗在第一种情况下,p是倒数第二个元素的下一个值,在第二种情况下,p是倒数第三个元素的下一个值,所以p->next应该是倒数第二个元素的下一个值。这是结构:

struct lista{
    int val;
    lista *next;
};


错误发生在'delete...;'行中

编辑本·福格特

为什么?如果我做这样的测试:

lista *p = head;
while (p->next->next != nullptr){
    p = p->next;
}
cout << p->next;
lista *z = head;
while (z->next != nullptr){
    z = z->next;
}
cout << endl << z;


p和z都是0x 5575909 e3 eb 0,它们不是一样的吗?

6yoyoihd

6yoyoihd1#

问题是,在失败的代码中,您正在释放列表中的最后一项,而没有将其从列表中删除。结果是包含悬挂指针的列表,因此后续遍历列表的操作具有未定义的行为。
工作代码将其从列表中分离出来。
为了回答你的思想实验,让我们把它变得更简单。

std::cout << head << '\n';
lista* z = head;
std::cout << z << '\n';

z = nullptr;
// now how many items are in the list?
std::cout << head << '\n';
std::cout << z << '\n';

// are `head` and `z` really equivalent?
z = head;
head = nullptr;
// now how many items are in the list?
std::cout << head << '\n';
std::cout << z << '\n';

字符串

相关问题