如果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;
- }