我正在努力熟悉Haskell的FFI,所以我写了这个小例子:
Main.hs:
{-# LANGUAGE ForeignFunctionInterface #-}
import Foreign.C.Types
import Foreign.Ptr (Ptr)
import Foreign.Marshal.Array (peekArray)
import Foreign.Marshal.Alloc (free)
foreign import ccall "test.h test"
test :: CInt -> Ptr CInt
main = do
let rval = test 6
-- print the array
list <- peekArray 6 rval >>= return . map toInteger
putStrLn $ show list
free rval
-- print it again (it should okay)
putStrLn $ show list
-- try to retrieve it AGAIN after I used free. Should print random values
peekArray 6 rval >>= return . map toInteger >>= putStrLn . show
test.h
#ifndef TEST_H
#define TEST_H
int* test(int a);
#endif
test.c的
#include "test.h"
#include <stdio.h>
#include <stdlib.h>
int* test(int a)
{
int* r_val = (int*)malloc(a * sizeof(int));
r_val[0] = 1;
r_val[1] = 2;
r_val[2] = 3;
r_val[3] = 4;
r_val[4] = 5;
r_val[5] = 6;
return r_val;
}
编译并运行Main.hs
时得到的输出是:
D:\Code\Haskell\Projects\Dev\TestFFI>cabal build
Building TestFFI-0.1.0.0...
Preprocessing executable 'TestFFI' for TestFFI-0.1.0.0...
[1 of 1] Compiling Main ( src\Main.hs, dist\build\TestFFI\TestFFI-tmp\Main.o )
Linking dist\build\TestFFI\TestFFI.exe ...
D:\Code\Haskell\Projects\Dev\TestFFI>
D:\Code\Haskell\Projects\Dev\TestFFI>dist\build\TestFFI\TestFFI.exe
[1,2,3,4,5,6]
[1,2,3,4,5,6]
[1,2,3,4,5,6]
这似乎对我没有任何意义。我第三次打印数组时,我期待的是:
[69128391783,2083719073,934857983457,98374293874,0239823947,2390847289347]
随机数据!
我做错了吗?我错过了什么吗?
答案 0 :(得分:8)
在释放内存后读取内存是未定义的行为。任何事情都是允许的 - 包括返回随机数据,召唤鼻子恶魔,甚至是在可能的世界中,在它被释放之前返回该内存中的数据。