Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4464049
  • 博文数量: 356
  • 博客积分: 10458
  • 博客等级: 上将
  • 技术积分: 4734
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-24 14:59
文章分类

全部博文(356)

文章存档

2020年(17)

2019年(9)

2018年(26)

2017年(5)

2016年(11)

2015年(20)

2014年(2)

2013年(17)

2012年(15)

2011年(4)

2010年(7)

2009年(14)

2008年(209)

分类: C/C++

2019-05-23 10:59:07

std::list为empty时调用pop_front导致程序崩溃
如果list中装的是指针,当其为empty时,再调用pop_front可能会返回一个非NULL的值,此时直接使用这个返回的指针会导致内存越界。

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <iostream>
  4. #include <list>
  5. #include <unistd.h>
  6. #include <assert.h>

  7. using namespace std;

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

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

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

  24. void Test2() // pass
  25. {
  26.     std::list<int> list2;
  27.     int n = 1;

  28.     while (1)
  29.     {
  30.         list2.push_back(n);
  31.         std::cout << "size:" << list2.size() << " front:" << list2.front() << std::endl;
  32.         list2.pop_front();
  33.         std::cout << "size:" << list2.size() << " front:" << list2.front() << std::endl;

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

  39.     int
  40. main( int argc, char **argv )
  41. {
  42.     Test2();
  43.     Test();

  44.     return 0;
  45. }
作者:帅得不敢出门 

阅读(266751) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~