我正在摆弄 OCaml Unix 模块,看看它是否会拒绝包含某些字节的字符串,这些字节可能在给定系统调用的上下文中产生令人惊讶的效果并抛出异常。例如。 Unix.create_process
的 prog
参数中的空字节,或 env : string array
参数中的字符串之一中的换行符。
我尝试了几种方法在字符串中包含空字节,例如 "/bin/ls\0"
(这是字符串文字中的非法转义序列)和 "/bin/ls"^ string_of_char '\0'
(这是字 rune 字中的非法序列)。最后,我将零转换为字符串,然后创建一个包含空字符的长度为 1 的字符串,然后将其与我的字符串连接起来。
module U = Unix;;
let string_of_char ch : string = String.make 1 ch
let sketchy_string = "/bin/ls" ^ string_of_char (char_of_int 0)
let _ = U.create_process sketchy_string [|"ls"|] U.stdin U.stdout U.stderr
向 ocaml 字符串添加空字节的正确方法是什么?
最佳答案
您可以使用通用的“十六进制代码”转义序列来写入空字节(或您想要的任何其他字节):
let null_byte = '\x00';;
let sketchy_string = "/bin/ls\x00";;
如需进一步引用,请参阅 Ocaml 手册中涉及转义序列的部分:http://caml.inria.fr/pub/docs/manual-ocaml/lex.html#escape-sequence
关于ocaml - 在 OCaml 中的字符串中包含空字符/字节的惯用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36993643/