分段错误:11迭代argv的参数时

时间:2014-04-22 11:23:40

标签: c++ segmentation-fault llvm

我编写了这个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。

1 个答案:

答案 0 :(得分:3)

分段错误是由于内存访问冲突 - 解除引用无效指针:

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]));
}

我建议使用debuger。它会显示导致故障的行,以便您可以调查无效指针。


也改为:

for( int i=0; i < args.size(); ++i)
{
    arg = args.front();