gpt4 book ai didi

memory - 释放用 newCString 分配的内存

转载 作者:IT王子 更新时间:2023-10-28 23:33:27 24 4
gpt4 key购买 nike

正如库文档所说,使用 newCString 创建的 CString 必须使用 free 函数释放。我一直期待在创建 CString 时会占用一些内存,而当使用 free 释放它时,内存使用率会下降,但事实并非如此!这是示例代码:

module Main where

import Foreign
import Foreign.C.String
import System.IO

wait = do
putStr "Press enter" >> hFlush stdout
_ <- getLine
return ()

main = do
let s = concat $ replicate 1000000 ['0'..'9']
cs <- newCString s
cs `seq` wait -- (1)

free cs
wait -- (2)

当程序在 (1) 处停止时,htop 程序显示内存使用量在 410M 左右 - 这没关系。我按回车,程序在第 (2) 行停止,但尽管 csfreed!

,但内存使用量仍为 410M

这怎么可能?用 C 编写的类似程序的行为应如此。我在这里错过了什么?

最佳答案

问题是 free 只是向垃圾收集器表明它现在可以收集字符串。这实际上并没有强制垃圾收集器运行——它只是表明 CString 现在是垃圾。仍然由 GC 根据堆压力启发式决定何时运行。

您可以强制在调用 free 之后直接调用 performGC,这会立即将内存减少到 5M 左右。

例如这个程序:

import Foreign
import Foreign.C.String
import System.IO
import System.Mem

wait = do
putStr "Press enter" >> hFlush stdout
_ <- getLine
return ()

main = do
let s = concat $ replicate 1000000 ['0'..'9']
cs <- newCString s
cs `seq` wait -- (1)

free cs
performGC
wait -- (2)

表现如预期,具有以下内存配置文件 - 第一个红点是对 performGC 的调用,立即解除分配字符串。然后程序在 5M 左右悬停直到终止。

enter image description here

关于memory - 释放用 newCString 分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10513007/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com