-2

I am getting segfault error when I tried the following. I am getting some arguments dynamically to the program. I have to concatenate all of them into a single string and operate on it. I have written the following code for concatenating all the arguments into one string.

   int main(int argc, char** argv){
   string input;
   for(int i=1;i<=argc;i++)
       {

            input+= argv[i]+string(" ");

       }
       //code for operating on the string. code not yet written
   return 0;
   }

I am getting segfault when the arguments are more. If the arguments are 10-20, then there is not segfault. But when the arguments are 100, I am getting segfault. I tried using char[] in c++. but that also giving the same error. How to handle this?

SARATH
  • 51
  • 8

1 Answers1

3

The comparison in your for loop is wrong. You are checking for less-than or equal to instead of just less than.

The following line

for(int i=1;i <= argc;i++)
//            ^^

should be

for(int i=1;i < argc;i++)
//            ^
Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
  • Note that argv[argc] is not out of bounds memory and is defined to be a NULL pointer. (http://stackoverflow.com/questions/3772796/argvargc) – Cookyt Dec 24 '13 at 08:02
  • Quite correct. Thanks, updated. – Captain Obvlious Dec 24 '13 at 08:08
  • Thanks @CaptainObvlious. I have put it because in my unix sys, argv[0] was giving the program name. SO, I thought I should loop from 1 to argc instead of 0 to argc-1. Thank you very much!! – SARATH Dec 27 '13 at 05:41