Can address space be recycled for multiple calls to MapViewOfFileEx without chance of failure?

前端 未结 4 738
自闭症患者
自闭症患者 2021-01-14 06:13

Consider a complex, memory hungry, multi threaded application running within a 32bit address space on windows XP.

Certain operations require n large buffers of fixed

4条回答
  •  轮回少年
    2021-01-14 06:22

    Imagine if I came to you with a piece of code like this:

    void *foo;
    
    foo = malloc(n);
    if (foo)
       free(foo);
    foo = malloc(n);
    

    Then I came to you and said, help! foo does not have the same address on the second allocation!

    I'd be crazy, right?

    It seems to me like you've already demonstrated clear knowledge of why this doesn't work. There's a reason that the documention for any API that takes an explicit address to map into lets you know that the address is just a suggestion, and it can't be guaranteed. This also goes for mmap() on POSIX.

    I would suggest you write the program in such a way that a change in address doesn't matter. That is, don't store too many pointers to quantities inside the buffer, or if you do, patch them up after reallocation. Similar to the way you'd treat a buffer that you were going to pass into realloc().

    Even the documentation for MapViewOfFileEx() explicitly suggests this:

    While it is possible to specify an address that is safe now (not used by the operating system), there is no guarantee that the address will remain safe over time. Therefore, it is better to let the operating system choose the address. In this case, you would not store pointers in the memory mapped file, you would store offsets from the base of the file mapping so that the mapping can be used at any address.

    Update from your comments

    In that case, I suppose you could:

    • Not map into contiguous blocks. Perhaps you could map in chunks and write some intermediate function to decide which to read from/write to?

    • Try porting to 64 bit.

提交回复
热议问题