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

猜你喜欢

转载自www.cnblogs.com/Malphite/p/11566959.html