11

Assuming that EXE and DLL use the same compiler and STL version. If I use a std::vector in my EXE and use reserve to reserve memory. Then I pass it as reference to a DLL.

I do a push_back in the DLL to add an element to my vector. If I do not exceed actual capacity, is the memory of the new element allocated in the DLL or in the EXE ?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
FSeywert
  • 111
  • 5

2 Answers2

3

This is generally a bad idea.

When you call push_back, a copy can be made of whichever object you are adding to the vector. There is no guarantee that the size of that object (among other things) is the same as the size reserved in the .exe via std::vector::reserve. Both binaries may have been compiled with a different version of the STL.

Community
  • 1
  • 1
lcs
  • 4,227
  • 17
  • 36
  • Ok I understand, but assuming that the vector capacity is big enough and all restrictions about binaries (compilator, libraries, exceptions settings, ...) are met. Is it ok to do that (under a memory point of view) ? In others words, if the DLL is released after that, is the data still exist and is accessible? – FSeywert Jun 08 '15 at 15:48
  • 1
    Assuming everything lines up perfectly, sure. However it is still a bad idea to pass things across the DLL boundary. You should look for a different solution for sharing the information you need. (ie, allocate the vector in the DLL and return a reference to the EXE). – lcs Jun 08 '15 at 15:58
0

Neither.

It's allocated in the virtual memory space of the process, whose code is a combination of the .exe and the .dll.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 6
    Uhm, no. A DLL uses - in general - a different memory allocator, and you should not pass resources across a DLL boundary. See [Potential Errors Passing CRT Objects Across DLL Boundaries](https://msdn.microsoft.com/en-us/library/ms235460.aspx) for reference. – IInspectable Jun 08 '15 at 15:22
  • If both the EXE and the DLL are built with the same VC++ compiler and settings and dynamically link to the same CRT flavor (which I know is very constraining), then I believe Lightness' answer is correct. If you build a test EXE and DLL and call `_get_heap_handle()` from each one, you'll get the _same_ returned handle (at least, this is what I got in my tests). I was writing that in an answer, but unfortunately the question was (IMO incorrectly) closed, so I'm writing a comment here. – Mr.C64 Jun 08 '15 at 16:49
  • 3
    @Mr.C64: Even under the constraints you name, this answer is still wrong: Memory is never allocated in the virtual address space. It is allocated in a heap, whose memory is mapped into said address space. The heap is owned by the respective module. This distinction, while vital, is missing from the answer altogether. – IInspectable Jun 08 '15 at 17:21