GNU函数asprintf(打印到分配的字符串)是否是线程安全的?
(IIC,基本上,这归结为是否malloc是线程安全的问题.)
考虑示例代码:
#define _GNU_SOURCE
#include <stdio.h>
#include "getValue.h"
char * getValue(int key) {
char * value;
asprintf(&value, "%d", key); // TODO: No error handling!
// If memory allocation wasn't possible, or some other error occurs, these functions will
// return -1, and the contents of strp is undefined.
return value;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我不触及任何全局变量.如果我getValue在并发线程中调用了怎么办?没有坏事会发生,他们会吗?
我有一个C函数创建一个空终止字符串并返回一个指向它的指针,还有相应的释放函数.
foreign import ccall unsafe "get_str" getStr :: IO CString
foreign import ccall unsafe "free_str" freeStr :: CString -> IO ()
Run Code Online (Sandbox Code Playgroud)
我想从返回的CString创建一个Haskell字符串,并尽快释放CString.
do cStr <- getStr
str <- peekCString cStr
freeStr cStr
-- here str is used
Run Code Online (Sandbox Code Playgroud)
在使用str之前释放cStr是否安全?换句话说,peekCString是否一次创建Haskell String,还是懒得创建?