gpt4 book ai didi

python - 管道到 unistd.h 读取段错误

转载 作者:太空狗 更新时间:2023-10-29 11:46:10 27 4
gpt4 key购买 nike

我试图通过管道进入读取,但它在第二个输入后一直出现段错误。我究竟做错了什么?提前致谢。

 $ ./read < <(python -c 'print "BBA\nBBADD\n",')
Please enter your first name:
buf=
BBA
BBA
Please enter your last name:
buf=
Segmentation fault (core dumped)

我附上read的代码作为引用,重要的部分是read()

//read.c
#include <stdio.h>
#include <string.h>

void prompt_name(char *name, char *msg){
char buf[4096];

puts(msg);

read(0, buf, sizeof buf);
puts("buf=");
puts(buf);
*strchr(buf, '\n') = 0;

puts(buf);
strncpy(name, buf, 20);
puts(name);
}

void prompt_full_name(char *fullname) {
char last[20];
char first[20];

prompt_name(first, "Please enter your first name: ");
prompt_name(last, "Please enter your last name: ");

strcpy(fullname, first);
strcat(fullname, " ");
strcat(fullname, last);
}


int main(int argc, char **argv){
char fullname[42];

prompt_full_name(fullname);
printf("Welcome, %s\n", fullname);

return 0;
}

`

最佳答案

read 对字符串一无所知,因此它只是愉快地读取 sizeof(buf) 个字符,而不会以 NUL 终止 buf。然后调用 puts(buf) 会导致未定义的行为。

您不应该将此类低级函数用于简单的字符串 I/O;更喜欢 getline 代替。如果你确实想使用read,那么读取更小的 block ,检查每次调用的返回值并使用它;它会告诉您阅读了多少内容。

关于python - 管道到 unistd.h 读取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13291199/

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