Click here to Skip to main content
14,881,921 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to allocate memory to a pointer in main function, then pass it to a library function and free it there in the library function.

How to implement this?

Please help me....
Posted
Comments
ThatsAlok 7-Jul-11 2:32am
   
Doesn't understand the question. if you allocating memory in main function and passing it library function, then it would be duty of programmer to maintain life of pointer's memory!

   
Exactly like you said it.
have you tried? what problem did you faced?
   
Comments
IT-NEWBIE 6-Jul-11 5:55am
   
I 1st allocated a memory dynamically for a pointer in main function and pass it to library function. Now I tried to delete the memory there in library function. During compile time there is no error. And on run time while executing that line the code gets "debug assertion failed" message.

What I should do now?
Emilio Garavaglia 6-Jul-11 12:41pm
   
If the library is static, the problem is mostly in the compile / link order.
If the library is dynamic (or linking a dynamic library) you shouldn't do that, since the two function may not be sharing the same global variable space (the "new" function, returnn the pointer but also tracks what it returned in a global data-structure that "delete" must update consistently. But if the two calls are in different DLL, there maybe two different copy of those global structures, one faced by new and the other by delete, that "see" a call about something it doesn't know it has been allocated.
ThatsAlok 7-Jul-11 2:31am
   
i believe there would be memory leak, if acquired memory is not release properly!
Emilio Garavaglia 7-Jul-11 2:58am
   
between EXE/DLL-s yes (well: not properly a "leak": most likely an inconsistent allocator internal state). Though a completely static linking no. I asked to know what did he tried just to understand what situation should apply.

The problem is in the question: he asked "how". But the point is that, in certain situations, cannot be done.
As Joan said,
it is safe to use the referencing (or overpointing) of the pointers
for their stack passing (in any (de-)allocation contexts of the same process) :) :

extern void lib_alloc(int** ppInt);
//{
//  if (ppInt) {
//    *ppInt = new int[2];
//  }
//}

extern void lib_free(int** ppInt);
//{
//  if (ppInt) {
//    delete *ppInt;
//    *ppInt = NULL;
//  }
//}

void loc_test()
{
  int* pInt(NULL);
  lib_alloc(&pInt);
  lib_free(&pInt);
}
   
Dont' do that: Make both allocation and deallocation happen either in the library or in the application (see "Allocating and freeing memory across module boundaries"[^]).
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900