私は、1文字のテキスト文字列の引数を128文字以下の任意の数だけ使用するプログラムを作成しようとしています。プログラムはstdinからstdoutにテキストをコピーしますが、入力に表示されている単語のいずれかが "CENSORED"という単語に置き換えられます。このコードがセグメンテーションフォールトを与えているのはなぜですか?
例:
Said Hamlet to Ophelia,
I'll draw a sketch of thee,
What kind of pencil shall I use?
2B or not 2B?
プログラムは、この実行する必要があります:
./censor Ophelia < poem.txt
Said Hamlet to CENSORED,
I'll draw a sketch of thee,
What kind of pencil shall I use?
2B or not 2B?
をここに私のコードです:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char lines[200][200];
int numLines=0,i,j;
int nbytes = 128;
int bytes_read=0;
char *my_string;
char * pch;
//reading from stdin
while(stdin)
{
my_string=(char *) malloc (nbytes + 1);
bytes_read = getline (&my_string, &nbytes, stdin);
strcpy(lines[numLines++],my_string);
}
//scanning and replacing specified words by "CENSORED"
for(i=0;i<argc;i++)
{
for(j=0;j<numLines;j++)
{
pch = strstr (lines[j],argv[i]);
strncpy (pch,"CENSORED",8);
}
}
//display the result in output screen
for(j=0;j<numLines;j++)
{
printf("\n%s",lines[i]);
}
}
問題がある 私はpoem.txtと呼ばれるこのファイルを持っていますこれがセグメンテーション違反を与えているが、私は間違いを特定できません。
http://ericlippert.com/2014/03/05/how-to- debug-small-programs/ – Biffen
'argc'と' argv'の定義を見てください。ところで、あなたはsegフォルトが発生した場所を詳しく述べるべきです –
'while(stdin)'あなたはそれが何をすると思いますか? 'stdin'はいつまでも0になるのですか? – artm