英文:
Why is this string blank after the procedure returns it (Odin)?
问题
在以下的小示例程序中,从 stdin
读取输入。在 read_input
函数中,打印字符串值有效,但在 main
函数中不起作用。令人惊讶的是,在 main
函数中可以输出字符串的长度 (len
),但字符串本身却是空的。
main :: proc() {
fmt.print("$ ")
input := read_input()
// This will output the proper length
fmt.println("returned string length:", len(input))
// This will be empty
fmt.println("returned string: ", input)
}
read_input :: proc() -> string {
buf: [256]byte
num_bytes, err := os.read(os.stdin, buf[:])
if err < 0 {
return "Error reading from stdin"
}
str := string(buf[:num_bytes - 1])
// this will output the proper number of bytes
fmt.println("bytes read: ", num_bytes)
// this will output the string entered, minus the newline
fmt.println("read string: ", str)
return str
}
示例运行/输出:
$ hello
bytes read: 6
read string: hello
returned string length: 5
returned string:
我发现返回 strings.clone(str)
可行,但我并没有真正理解上面的问题。
英文:
In the following small sample program, input is read from stdin
. Printing the string value works inside read_input
, but not in main
. Surprisingly, the length (len
) of the string does output in main
, though the string output is blank.
main :: proc() {
fmt.print("$ ")
input := read_input()
// This will output the proper length
fmt.println("returned string length:", len(input))
// This will be empty
fmt.println("returned string: ", input)
}
read_input :: proc() -> string {
buf: [256]byte
num_bytes, err := os.read(os.stdin, buf[:])
if err < 0 {
return "Error reading from stdin"
}
str := string(buf[:num_bytes - 1])
// this will output the proper number of bytes
fmt.println("bytes read: ", num_bytes)
// this will output the string entered, minus the newline
fmt.println("read string: ", str)
return str
}
Example run/output:
$ hello
bytes read: 6
read string: hello
returned string length: 5
returned string:
I've discovered that returning strings.clone(str)
works but I'm not really understanding the problem above.
答案1
得分: 1
在Odin中,string
只是对底层数据缓冲区的一个视图。在您的情况下,它指向buf
,而buf
是局部于read_input
过程的。一旦read_input
返回,它的堆栈内存就消失了,但返回的字符串仍然指向它。
strings.clone(str)
之所以起作用,是因为它为字符串复制分配了内存,并返回指向这个内存的字符串。在这种情况下,您需要在main
函数中进行delete
操作,以避免内存泄漏。
英文:
In Odin string
is just a view over underlaying data buffer. In your case it points to buf
which is local to read_input
procedure. Once read_input
returns its stack memory is gone, but returned string still points to it.
strings.clone(str)
works because it allocates memory for a string copy and return string which points into this memory. In this case you'll need to delete
it in main
to avoid memory leak.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论