【发布时间】:2021-12-28 10:28:30
【问题描述】:
我正在了解std::allocator。我尝试分配但错误地使用 deallocate 我看到它没有使用 size 参数,我对方法感到困惑,你能解释一下吗?谢谢。
- testcase1 "test" : 我没有解除分配,检测到 valgrind(正确)
- testcase2 "test_deallocate" : 我释放的 size(0) 小于实际大小 (400),valgrind 或
-fsanitize=address无法检测到泄漏 - testcase3 "test_deallocate2": 我在 size(10000) 大于实际大小 (400) 的情况下解除分配,编译器没有警告,带有
-fsanitize=address的 g++ 也无法检测到这一点。
#include <iostream>
#include <memory>
using namespace std;
void test(){
allocator<int> al;
int* bl = al.allocate(100);
}
void test_deallocate(){
allocator<int> al;
int* bl = al.allocate(100);
al.deallocate(bl, 0);
}
void test_deallocate2(){
allocator<int> al;
int* bl = al.allocate(100);
al.deallocate(bl, 10000);
}
int main(){
test();
test_deallocate();
test_deallocate2();
return 0;
}
瓦尔格林:
valgrind --leak-check=full ./a.out
==12655== Memcheck, a memory error detector
==12655== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==12655== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==12655== Command: ./a.out
==12655==
==12655==
==12655== HEAP SUMMARY:
==12655== in use at exit: 400 bytes in 1 blocks
==12655== total heap usage: 4 allocs, 3 frees, 73,904 bytes allocated
==12655==
==12655== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==12655== at 0x483BE63: operator new(unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==12655== by 0x1090D1: allocate (new_allocator.h:114)
==12655== by 0x1090D1: test (test.cpp:8)
==12655== by 0x1090D1: main (test.cpp:27)
==12655==
==12655== LEAK SUMMARY:
==12655== definitely lost: 400 bytes in 1 blocks
==12655== indirectly lost: 0 bytes in 0 blocks
==12655== possibly lost: 0 bytes in 0 blocks
==12655== still reachable: 0 bytes in 0 blocks
==12655== suppressed: 0 bytes in 0 blocks
==12655==
==12655== For lists of detected and suppressed errors, rerun with: -s
==12655== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
【问题讨论】:
-
对
deallocate使用不正确的大小违反了其先决条件,导致未定义的行为。但这并不意味着该函数实际上需要使用该参数。链接问题中解释了为什么它在通常不使用时存在。 -
是的,@user17732522 谢谢,未定义的行为对我来说很模糊。我运行了一段时间的测试,因为我认为 valgrind 或静态分析之类的调试工具可以检测到问题。
-
“未定义行为”意味着 C++ 标准不保证任何事情。它不保证该程序会运行或不会运行。任何类型的分析器通常都无法检测到未定义的行为,尤其是在这种情况下,您只是违反了实际上可能无关紧要的标准库先决条件。
标签: c++ g++ valgrind allocator