gpt4 book ai didi

c++ - 段错误 : 11 when iterating over arguments of argv

转载 作者:行者123 更新时间:2023-11-28 00:30:18 26 4
gpt4 key购买 nike

我编写了这个 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();

关于c++ - 段错误 : 11 when iterating over arguments of argv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23218038/

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