making your own malloc function in C

前端 未结 4 2107
你的背包
你的背包 2021-01-03 09:01

I need your help in this. I have an average knowledge of C and here is the problem. I am about to use some benchmarks to test some computer architecture stuff (branch misses

4条回答
  •  鱼传尺愫
    2021-01-03 09:45

    Trying a thread safe nos answer given above, I am referring his code with some changes as below:

    static unsigned char our_memory[1024 * 1024]; //reserve 1 MB for malloc
    static size_t next_index = 0;
    
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    
    void *malloc(size_t sz)
    {
        void *mem;
        pthread_mutex_lock(&lock);
        if(sizeof our_memory - next_index < sz){
            pthread_mutex_unlock(&lock);
            return NULL;
        }
    
        mem = &our_memory[next_index];
        next_index += sz;
        pthread_mutex_unlock(&lock);
        return mem;
    }
    
    void free(void *mem)
    {
       //we cheat, and don't free anything.
    } 
    

提交回复
热议问题