简体   繁体   中英

How to check if a pointer is valid in C++?

I have been given an interview question to write a Memory Manager (memory pool). I am almost done, but I have problems with deallocating. It is also fine to ask for help, as along as we mention the sources of help. So please help me

int main(void)
{
  using namespace PoolOfMemory;

  initializePoolOfMemory(); // Initialize a char array as the memory pool

  long* int_pointer;

  int_pointer = (long *) allocate(sizeof(long)); //allocate is defined in PoolOfMemory and it returns void*.

  int_pointer = 0xDEADBEEF;

  deallocate(int_pointer);
}

Now my problem is that when "deallocate" tries to deallocate int_pointer, it throws an access violation error, obviously because I am trying to access 0xDEADBEEF. Below is my simple deallocate function:

void deallocate(void* p)
{
    Header* start = (Header*)((char*)p-sizeof(Header));
    start->free=true; //This is where I get access violation.;
}

How can I avoid this? I assume that checking if p is in my array, is not going to work, based on what I read on the net.

Memory managers do tend to be closer to the hardware level and may need to make decisions based on the operating system and CPU type they're used on.

In this case you may be able to justify breaking some of the C++ abstract machine rules. For example, just go ahead and compare your pointer with the boundaries of your pool array. Yes, this can go wrong on architectures that use segmented memory or that can form trap pointers, but what else are you going to do?

After that, to validate that you have a proper pointer you can have your allocator write a magic value into the allocation header block, which you can verify in the deallocate function before you start writing into free booleans and free block pointers, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM