[英]Why std::unique_lock changes std::unique_ptr?
我這里發生了一些奇怪的事情,至少對我來說很奇怪......
我有一個線程函數......
void run(std::mutex &mtx, std::condition_variable &cv)
{
std::unique_ptr<float[]> shiftbuf(new float[SHIFTBUF_SIZE]);
float *const shiftbuf_p = shiftbuf.get();
for (;;)
{
*(shiftbuf_p + SHIFTBUF_SIZE - 1) = 100.f;
std::unique_lock<std::mutex> lck(mtx);
cv.notify_all();
}
}
主要是......
std::mutex mtx;
std::condition_variable cv;
std::thread th(run, std::ref(mtx), std::ref(cv));
std::unique_lock<std::mutex> lck(mtx);
cv.wait(lck);
當我調試代碼並觀察shiftbuf_p
時, lck
上的地址發生了變化?!
Thread 18 "..." hit Hardware watchpoint 4: shiftbuf_p
Old value = (float * const) 0x7fffd8000b10
New value = (float * const) 0x7fffd8000b01
run (mtx=..., cv_second=..., amplitude_data=..., tm=...)
at ....cpp:132
132 std::unique_lock<std::mutex> lck(mtx);
(gdb) c
Continuing.
Thread 18 "..." hit Hardware watchpoint 4: shiftbuf_p
Old value = (float * const) 0x7fffd8000b01
New value = (float * const) 0x7fffd8000001
run (mtx=..., cv_second=..., amplitude_data=..., tm=...)
at ....cpp:132
132 std::unique_lock<std::mutex> lck(mtx);
(gdb) c
Continuing.
Thread 18 "..." hit Hardware watchpoint 5: shiftbuf_p
Old value = (float * const) 0x7fffd8000001
New value = (float * const) 0x7fff00000001
run (mtx=..., cv_second=..., amplitude_data=..., tm=...)
at ....cpp:132
132 std::unique_lock<std::mutex> lck(mtx);
(gdb) c
Continuing.
Thread 18 "..." received signal SIGSEGV, Segmentation fault.
而且它永遠不會變回正確的原始地址。 當run()
繼續shiftbuf_p
指向錯誤的地址。
為什么地址變了? 它是一個常量指針。 unique_ptr scope 在子線程中位於頂部。 等待調用在主線程中。
但shiftbuf.get()
也返回nullptr
。 就像 unique_ptr shiftbuf
退出 scope 一樣,但是這段代碼不應該發生這種情況,不是嗎?
你能解釋發生了什么嗎?
好的。 我想我找到了我的問題。
堆棧上還有另一個數據數組,這個數組被用來寫越界,因為它的索引完全失控了。 所以shiftbuf_p
地址可能會改變。
很難找到...沒有 -fstack-protector 或 valgrind 檢測到原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.