无论如何,是否可以解决 ndefinedBehaviorSanitizer 给出的错误

Are there anyways to work around errors given by ndefinedBehaviorSanitizer

我有以下代码:

#include <memory>
#include <functional>
#include <boost/lockfree/queue.hpp>

#define _ThreadPoolLength_  100

class thread_pool {
public:
    thread_pool() : q(_ThreadPoolLength_) {}

private:
    mutable boost::lockfree::queue<std::function<void(int id)> *> q;
};

class Worker
{
    thread_pool workerPool;
};

Worker* worker;

int main() {
    worker = new Worker();
    delete worker;
    return 0;
}

如果用 clang++ -fsanitize=address,undefined code.cpp 编译它,那么在 运行 期间它会产生如下内容:

constructor call on misaligned address 0x6060000025a0 for type 'boost::lockfree::queue *>::node', which requires 64 byte alignment 0x6060000025a0: note: pointer points here

01 00 00 3c 40 25 00 00 60 60 be be be be be be be be be be be be be be be be be be be be be be ^

#0 0x519fc5 in boost::lockfree::queue<std::function<void (int)>*>::node* boost::lockfree::detail::freelist_stack<boost::lockfree::queue<std::function<void (int)>*>::node, std::allocator<boost::lockfree::queue<std::function<void (int)>*>::node> >::construct<true, false, boost::lockfree::queue<std::function<void (int)>*>::node*>(boost::lockfree::queue<std::function<void (int)>*>::node* const&) 
#1 0x517e77 in boost::lockfree::queue<std::function<void (int)>*>::initialize() 
#2 0x51743c in boost::lockfree::queue<std::function<void (int)>*>::queue(unsigned long) 
#3 0x51713f in thread_pool::thread_pool() 
#4 0x517048 in Worker::Worker() 
#5 0x516ed9 in main 
#6 0x7f6c3cb6bb96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#7 0x41a5f9 in _start

SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior ...

我怀疑这些错误是由 boost::lockfree::queue<std::function<void(int id)> *> 引起的,但为什么呢?有什么办法可以解决这个问题吗?

clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)

最后参考a blog post.

boost::lockfree::queue<std::function<void(int id)> *>的用法换成了类似的class

您正在泄漏 worker,因为您使用 new 构建它而从未使用 delete 破坏它。其他 ASan 消息在那里是因为作为构建 worker 的一部分,它的成员队列也被构建。