• c++ list的坑


    std::list为空时调用pop_front的访问越界问题

    std::list为空时调用pop_back访问越界问题

    所以在使用pop_front 、 pop_back要先判断list是否为空

    std::list为empty时调用pop_front导致程序崩溃


    如果list中装的是指针,当其为empty时,再调用pop_front可能会返回一个非NULL的值,此时直接使用这个返回的指针会导致内存越界。
    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #include <list>
    #include <unistd.h>
    #include <assert.h>

    using namespace std;

    void Test() // failed
    {
    std::list<int *> list;
    int n = 1;
    std::cout << "n address:" << static_cast<void *>(&n) << std::endl;

    while (1)
    {
    list.push_back(&n);
    std::cout << "size:" << list.size() << " front:" << static_cast<void *>(list.front()) << std::endl;
    list.pop_front();
    std::cout << "size:" << list.size() << " front:" << static_cast<void *>(list.front()) << std::endl;

    if (list.empty())
    assert(list.front() == NULL); // 这里会断言失败,若list中为指针时在pop_front前一定要先检查下是否为空,否则会导致访问越界
    usleep(1000*500);
    }
    }

    void Test2() // pass
    {
    std::list<int> list2;
    int n = 1;

    while (1)
    {
    list2.push_back(n);
    std::cout << "size:" << list2.size() << " front:" << list2.front() << std::endl;
    list2.pop_front();
    std::cout << "size:" << list2.size() << " front:" << list2.front() << std::endl;

    if (list2.empty())
    assert(list2.front() == 0); // 这里断言成功
    usleep(1000*500);
    }
    }

    int
    main( int argc, char **argv )
    {
    Test2();
    Test();

    return 0;
    }

    转自:https://blog.csdn.net/zmlovelx/article/details/90476306

  • 相关阅读:
    重置root密码
    JavaEE完整体系架构
    Analysis servlet injection
    隔离级别
    ULVAC爱发科皮拉尼真空计SW1-N说明书-手册
    研华advantech-凌华ADLINK板卡运动控制卡
    vc6.0转vs2012的一些错误与解决方法
    MFC时间简单比较方法
    MFC_VC++_时间获取与保存列表控件内容到文件操作方法
    show and hide. xp扩展名
  • 原文地址:https://www.cnblogs.com/Malphite/p/11566959.html
Copyright © 2020-2023  润新知