Hello everyone, there are 2 questions:

  1. Is it correct to clear the memory in the same way as in the code if the calc function is located in a separate dll? If not, how is it right? Or are there any other options?
  2. Why in the arguments of the function calc it is necessary to write a reference to the pointer Test * & test, and not Test * test?

    #include <iostream> using namespace std; struct Test { int a; int b; }; **// Эта функция будет в dll** void calc(Test *& test, unsigned int &sizeTest) { sizeTest = 3; test = new Test[sizeTest]; for (uint i = 0; i < sizeTest; i++) { test[i].a = i; test[i].b = i; } } int main() { Test *test = NULL; unsigned int sizeTest = 0; calc(test, sizeTest); cout << sizeTest << endl; for (uint i = 0; i < sizeTest; i++) { cout << test[i].a << endl; cout << test[i].b << endl; } // Корректно ли тут очищать память, выделенную в другой функции? delete[] test; return 0; } 
  • 2
    1. If the memory manager is guaranteed to be "common" then it is possible. But it rarely occurs. And if the dll has its own heap and the exe has its own, then clearly nothing good will come. 2. When assigning a variable of type *& reference & will affect the penemen in the calling function (you have this test), and without & your test will be NULL. - nick_n_a

1 answer 1

  1. In general, this is not possible. You can run into problems. Memory allocated in dll must be freed in dll. Because the memory manager of the process and the dll may be different. If you need to allocate so much memory in the dll and transfer it to the calling process, then you can also provide in the dll the function of releasing such memory, which the process should call.
  2. A pointer is a variable (memory cell) storing the address of another variable. Function parameters are essentially separate variables that are created for each function call, and to which you assign a value when you call it. Therefore, to change the value of a pointer using a function, it is necessary that the parameter be a pointer reference. In fact, internally, a link is also a pointer, just the syntax for working with it is as with a variable. That is, when you pass a link to a pointer, you essentially pass a pointer to a pointer. And if you just pass the pointer not by reference, then you pass the copy of the pointer, and you copy this copy inside the function and assign it the value of the address of the allocated memory.

Without references, your function would look like this:

 void calc(Test ** test, uint * sizeTest) { *sizeTest = 3; *test = new Test[*sizeTest]; for (uint i = 0; i < *sizeTest; i++) { (*test)[i].a = i; (*test)[i].b = i; } } // использование Test * array = nullptr; uint size = 0; calc(&array, &size);