Code Snippet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env stack
{- stack
   --resolver lts-12.0
   --install-ghc
   script
   --ghc-options -Werror
   --ghc-options -Wall
   --
-}

{-# LANGUAGE Safe #-}

--------------------------------------------------------------------------------

module Main (main) where

--------------------------------------------------------------------------------

import           Data.Word
  ( Word8
  )
import           Foreign.Marshal.Alloc
  ( free
  , mallocBytes
  )
import           Foreign.Ptr
  ( Ptr
  )
import           Foreign.Storable
  ( peekByteOff
  , pokeByteOff
  )

--------------------------------------------------------------------------------

readBytes :: Ptr Word8 -> Int -> IO ()
readBytes p i =
  mapM_ (\n -> word8 n >>= putStrLn . show) [ 0 .. (i - 1) ]
  where
    word8 = peekByteOff p :: Int -> IO Word8

saveBytes :: Ptr Word8 -> Int -> Word8 -> IO ()
saveBytes p i b =
  mapM_ (\n -> pokeByteOff p n b) [ 0 .. (i - 1) ]

main :: IO ()
main =
  do
    putStrLn "# We allocate bytes: "
    putStrLn $ show n
    p <- mallocBytes n
    putStrLn "# Pointer to bytes: "
    putStrLn $ show p
    putStrLn "# Initial bytes: "
    readBytes p n
    putStrLn "# Updated bytes: "
    saveBytes p n b
    readBytes p n
    putStrLn "# We free bytes (pointer): "
    putStrLn $ show p
    free p
    where
      n = 016
      b = 127 :: Word8

Code Output:

user@personal:~/../malloc/lib$ ./Main.hs
# We allocate bytes: 
16
# Pointer to bytes: 
0x00007c5c74000b30
# Initial bytes: 
0
11
0
116
92
124
0
0
0
0
0
0
0
0
0
0
# Updated bytes: 
127
127
127
127
127
127
127
127
127
127
127
127
127
127
127
127
# We free bytes (pointer): 
0x00007c5c74000b30

References: