Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to manage allocated memory in the foreign language?

My case is pretty simple: I have a C++ application and a Haskell library, and I just need to export from Haskell a function that would return a C string.

The issue is that the C string is originally a String, and to get a C string out of it I need to allocate storage which will have to be explicitly deallocated (Haskell's free or finalizerFree, as the documentation for newCString says).

What's a good way to handle that? Specifically I've got a few considerations:

Ideally I'd like to somehow let the Haskell runtime GC handle that, but I'm not sure how it could possibly know when and when not the memory is still needed by the foreign side. Is it possible?

If not, can I just call C's free or is the CString storage maintained by the Haskell runtime? if not I suppose I'll have to export Haskell's free as-well and call it from the foreign side, correct?

like image 469
MasterMastic Avatar asked Jan 22 '15 21:01

MasterMastic


People also ask

What is memory management in programming languages?

Memory management is the process of controlling and coordinating a computer's main memory. It ensures that blocks of memory space are properly managed and allocated so the operating system (OS), applications and other running processes have the memory they need to carry out their operations.

Which language has the best memory management?

As for internal memory management, Java has the best of the three, since it automates disposing of objects.

How programming languages use memory?

Computer programs need to allocate memory to store data values and data structures. Memory is also used to store the program itself and the run-time system needed to support it. If a program allocates memory and never frees it, and that program runs for a sufficiently long time, eventually it will run out of memory.

How do you manage memory in C++?

We can perform memory management in C++ with the use of two operators: new operator to allocate a block of memory on heap. delete operator to deallocate a block of memory from heap.


1 Answers

You do have to deallocate the string: as you say, there's no way Haskell's GC can know if that's still needed in the foreign side.

Haskell's free is exactly equivalent to C's free. You can call either, from the side you prefer.

free :: Ptr a -> IO ()
free  = _free

foreign import ccall unsafe "stdlib.h free"    _free    :: Ptr a -> IO ()

I didn't check if this is mandated by the Haskell report + FFI Addendum, but I'd guess so.

like image 71
chi Avatar answered Sep 20 '22 15:09

chi