[英]Segmentation fault: 11 when iterating over arguments of argv
我编写了此C ++程序,旨在重现echo命令:
#include <iostream>
#include <queue>
#include <string>
#include <iterator>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
//Step 1: convert a silly char*[] to queue<string>
queue<string> args;
for(int i=1;i<=argc;i++)
{
args.push(string(argv[i]));
}
//Step 2: Use this queue<string> (because a non-used variable, that's useless)
string arg, var, tos;
bool showEndl = true;
for(int i=0;i<=argc;i++) //The implementation of for arg in args is so crazy
{
arg = args.front(); //I can do arg = args[i] but that's not for nothing I make a queue. The cashier, she takes the customer front, she does not count the number of customers.
args.pop(); //Pop the arg
if(arg[0] == '$') //If that's a variable
{
var = ""; //Reset the variable 'var' to ''
for(string::iterator it=arg.begin();it!=arg.end();it++) //Because C++ is so complicated. In Python, that's just var = arg[1:]
{
var += *it;
}
tos += string(getenv(var.c_str()));
tos += ' ';
}
else if(arg == "-n") //Elif... No, C++ do not contains elif... Else if this is the -n argument.
{
showEndl = false;
}
else
{
tos += arg;
tos += ' ';
}
}
//Step 3 : Show the TO Show string. So easy.
cout << tos;
//Step 4 : Never forget the endl
if(showEndl)
{
cout << endl;
}
string a;
}
它可以很好地编译,但是当我运行它时,它在控制台中告诉我“ Segmentation fault:11”。 我使用LLVM。 那是什么意思? 为什么会这样呢?
PS:我使用LLVM。
分段错误是由于违反了内存访问-取消引用了无效的指针:
for( int i = 1; i <= argc; i++)
{
args.push( string( argv[ i]));
}
当有argc
参数发送到程序时,最后一个参数用argc - 1
索引。
for( int i = 0; i < argc; i++) // includes also a name of a program, argv[ 0]
{
args.push( string( argv[ i]));
}
要么:
for( int i = 1; i < argc; i++) // excludes a name of a program, argv[ 0]
{
args.push( string( argv[ i]));
}
我建议使用调试器。 它会向您显示导致故障的行,以便您可以调查无效的指针。
也更改为:
for( int i=0; i < args.size(); ++i)
{
arg = args.front();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.