簡體   English   中英

分段錯誤:遍歷argv參數時出現11

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM