How can I store a value at a specific location in the memory?

前端 未结 4 1294
鱼传尺愫
鱼传尺愫 2020-12-03 12:23

Maybe this is an easy question question but I would really like to know it for sure.

If I want to store a value, say an int, at a specific address in the memory (at

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 12:37

    I beleieve that the best way to achive your goal is implement your own malloc which will allocate 4 bytes more and store size of memory block like:

    void* mymalloc(int size)    
    {
        char* ptr = malloc(size+sizeof(int));
        memcpy(ptr, &size, sizeof(int));
        return ptr+sizeof(int); 
    }
    

提交回复
热议问题