dave_p_r_b
asked on
DLL function: returning a string -confusion-
Hi.
I've written a dll, I want that dll to return a string.
example:
extern "C" __declspec(dllexport) char* getString()
{
//do stuff
return "a string";
}
My question is about memory. I _think_ in this code I am returning a pointer to the string but if the memory is allocated in the dll, when is it deleted?
If the pointer to the string and the memory for the string is allocated within the dll, why is it that my application (that uses the dll/function) has access to this locally allocated value?
As you can see, I'm confused. How SHOULD I return a string? If I allocate it on the heap, can I delete it in the calling process?
Brief explaination would be appreciated.
Regards,
David.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
(I was refering to your second example).
The EXE and the DLL access the same memory space : the process memory space.
A DLL can allocate space that will be deleted by the EXE, and the opposite is also true.
A DLL can allocate space that will be deleted by the EXE, and the opposite is also true.
ASKER
//DLL function :
extern "C" __declspec(dllexport) char* getString()
{
char* s = new char[10];
strcpy(s, "a string");
return s;
}
//exe function :
int _tmain(int argc, _TCHAR* argv[])
{
//stuff
s = getString(); // s receives the same value as it is given in the dll
delete s; //ASSERTs here
}
//-----------------
in dbgheap.c
/*
* If this ASSERT fails, a bad pointer has been passed in. It may be
* totally bogus, or it may have been allocated from another heap.
* The pointer MUST come from the 'local' heap.
*/
_ASSERTE(_CrtIsValidHeapPo
This assert fires. I assume as the addresses of s are the same, it is not a bad pointer. Is that a fair assumption?
Thanks for your help
Regards,
David.
You should do "delete [] s;" since s is an array.
>A DLL can allocate space that will be deleted by the EXE, and the opposite is also true.
NO!
If you allocate in DLL you have to free in the same DLL
If you allocate in EXE you have to free in the same EXE
NO!
If you allocate in DLL you have to free in the same DLL
If you allocate in EXE you have to free in the same EXE
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks to all.
Brilliant answer macrom.... thank you.
Brilliant answer macrom.... thank you.
ASKER
How is it possible to delete a value that is not on the local heap? surely this would cause an exception? No?
Regards,
David.