Question

I write this C++ program, destinated to reproduce the echo command :

#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;
}

It compiles fine, but when I run it, it tells me "Segmentation fault: 11" in the console. I use LLVM. What that means? Why that makes that?

PS : I use LLVM.

Was it helpful?

Solution

The segmentation fault is due to memory access violation - dereferencing invalid pointer:

for( int i = 1; i <= argc; i++)
{
    args.push( string( argv[ i]));
}

When there are argc arguments sent to a program the last one is indexed with argc - 1.

for( int i = 0; i < argc; i++)  // includes also a name of a program, argv[ 0]
{
    args.push( string( argv[ i]));
}

or:

for( int i = 1; i < argc; i++)  // excludes a name of a program, argv[ 0]
{
    args.push( string( argv[ i]));
}

I suggest a use of debuger. It will show you the line causing a fault so you can investigate invalid pointer.


Change also to:

for( int i=0; i < args.size(); ++i)
{
    arg = args.front();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top