簡體   English   中英

管道傳輸到unistd.h讀取段錯誤

[英]Piping to unistd.h read segfault

我試圖通過管道讀取,但在第二次輸入后仍然保持段錯誤。 我究竟做錯了什么? 提前致謝。

 $ ./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 ,則讀取較小的塊,檢查每個調用的返回值並使用它; 它告訴您讀了多少書。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM