mohaps / lrucache11

A header only C++11 LRU Cache template class that allows you to define key, value and optionally the Map type. uses a double linked list and a std::unordered_map style container to provide fast insert, delete and update No dependencies other than the C++ standard library. This is a C++11 remake of my earlier LRUCache project (https://github.com/mohaps/lrucache) The goal was to create a fast LRUCache header only library and to avoid any dependencies like boost.
https://github.com/mohaps/lrucache11
294 stars 63 forks source link

double free or corruption (fasttop) #18

Open ChinaChenp opened 4 years ago

ChinaChenp commented 4 years ago

hi,i use you source code , but when i test many times, it will case a bug like this:

Error in `./../../build64_release/cplusutils/lrucache/lrucache_test': corrupted double-linked list: 0x00007f03c80008d0 ======= Backtrace: ========= /lib64/libc.so.6(+0x7b9e3)[0x7f04bf1a69e3] /lib64/libc.so.6(+0x7c4fe)[0x7f04bf1a74fe] ./../../build64_release/cplusutils/lrucache/lrucache_test[0x40d1a4] /lib64/libstdc++.so.6(+0xb52b0)[0x7f04bfabb2b0] /lib64/libpthread.so.0(+0x7e25)[0x7f04bfd15e25] /lib64/libc.so.6(clone+0x6d)[0x7f04bf22334d]

I finnally find the two members define order is wrong:
Map cache_; listtype keys;

I think correct should be like this: listtype keys; Map cache_;

cculianu commented 4 years ago

Hi,

Are you testing in a multithreaded app?

I am reviewing the code to this header to evaluate if I can use it in my project. I think the issue is that both get() and getCopy() are not thread safe, even if you instantiate the template with a real mutex.

While they guard access to the cache via a lock guard -- They release the lock when returning and get() returns a reference to internal cache data, while getCopy is just a wrapper around get() that does a copy-construct around the const Value & returned from get().

The real fix to all of this is to implement a getCopy() that holds the lock while it constructs the returned object, and only use getCopy() in multithreaded environments.

@mohaps Thoughts on this?

I am thinking of opening up an issue for thread-safety,

cculianu commented 4 years ago

See #19