内存在分配块之前被破坏 [英] memory clobbered before allocated block

查看:411
本文介绍了内存在分配块之前被破坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过几天的痛苦调试后,我可以用这个小程序在我的单元测试中重现一个错误:

After a few days of painful debugging, I could reproduce a bug in one of my unit test with this small program:

#include <iostream>
#include <vector>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <chrono>
#include <new>

int main(){
    try{
        for(size_t j=0;j<100;++j){
            std::cout<<j<<std::endl;
            std::mutex mutex;
            std::unique_ptr<std::condition_variable>cv;
            std::vector<std::thread>v(10);
            auto wait=[&](size_t i){
                std::unique_lock<std::mutex>ul(mutex);
                if(!cv){cv=std::make_unique<std::condition_variable>();}
                cv->wait_for(ul,std::chrono::milliseconds(i*10));
            };
            for(size_t i=0;i<v.size();++i){v[i]=std::thread(wait,i);}
            for(size_t i=0;i<v.size();++i){v[i].join();}}}
    catch(...){
        std::cout<<"Exception"<<std::endl;
        std::abort();}
}

lmcheck on:

When I compile with lmcheck on:

g++-4.9.2 -lmcheck -std=c++1y -pthread /home/Arnaud/Test.cpp -o Test

程序运行并停止,

我可以在多台机器上同时使用gcc 4.9.2和gcc 5.1来重现这一点。 此代码有什么问题?

I could reproduce this on multiple machines and both with gcc 4.9.2 and gcc 5.1. What is wrong with this code?

注意:此代码可在Visual Studio 2013中正常运行。

NB: This code runs fine with Visual Studio 2013.

推荐答案

根据本文档 mcheck 不是线程安全的。

According to this documentation, mcheck isn't thread-safe.

链接 -lmcheck 添加调用 mcheck 的分配钩子,这意味着它不再安全地分配和释放多个线程没有额外的同步。

It looks like linking with -lmcheck adds allocation hooks which call mcheck, meaning that it's no longer safe to allocate and deallocate memory from multiple threads without extra synchronisation.

这篇关于内存在分配块之前被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆