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

267180阅读 0评论2019-05-23 帅得不敢出门
分类:C/C++

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. }
作者:帅得不敢出门 

上一篇:交叉编译curl并支持http2
下一篇:交叉编译mpg123