我写了一个处理命令行输入的程序。当长字符串用作输入时,我在memcpy()函数期间出现分段错误。
以下是代码:
int main(int argc, char * argv[])
{
// initialize input variables
char inputFileName[] = "sequence.txt"; //default input file name
//check if a different file name is given
for(int i = 0; i < argc-1; i++){
if(string(argv[i])=="-i"){
cerr << "string: " << string(argv[i+1]).c_str() << endl;
cerr << "string size: " << string(argv[i+1]).size() << endl;
inputFileName[string(argv[i+1]).size()]=0;
cerr << "filename: " << inputFileName << endl;
memcpy(inputFileName,string(argv[i+1]).c_str(),string(argv[i+1]).size());
cerr << "filename after memcpy: " << inputFileName << endl;
break;
}
}
}
当给出短文件名(-i sequence.fasta)时,它可以正常工作:
$ ./Program -i sequence.fasta
string: sequence.fasta
string size: 14
filename: sequence.txt
filename after memcpy: sequence.fasta
filename final: sequence.fasta
然而,长名称会导致分段错误:
$ ./Program -i sequencesequencesequencesequencesequencesequencesequencesequencesequencesequence.fasta
string: sequencesequencesequencesequencesequencesequencesequencesequencesequencesequence.fasta
string size: 86
filename: sequence.txt
Segmentation fault: 11
我错过了什么吗?我该如何处理memcpy()?
答案 0 :(得分:1)
这是你的问题:
inputFileName[string(argv[i+1]).size()]=0;
inputFileName的预定义大小等于strlen(“sequence.txt”)+ 1 == 12bytes + 1byte for'\ 0'
char inputFileName[] = "sequence.txt"; //default input file name
所以,如果你使用字符串(argv [i + 1])。size()对其进行索引,那么如果argv [i + 1]长于13,则行为是未定义的。
你应该使用std :: string作为缓冲区
答案 1 :(得分:0)
除了数组的大小
char inputFileName[] = "sequence.txt";
是固定的,等于13您的代码有另一个错误。执行memcpy
时memcpy(inputFileName,string(argv[i+1]).c_str(),string(argv[i+1]).size());
然后你不复制终止零,因为表达式string(argv[i+1]).size()
没有考虑到它。