Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 60
  • Last Modified:

Why am I getting a seg fault?

Here's the code

int main(int argc, char* argv[1])
{
char charOld = argv[4][0];
char charNew = argv[5][0];
}
~

Open in new window


I know I'm not seeing something simple. What am I over looking in terms of the seg fault??
0
cgunix
Asked:
cgunix
2 Solutions
 
Mark BullockQA Engineer IIICommented:
argv is an array of char*, which point to strings.
argv[0] contains a pointer to the first string, the name or pathname of the program.
argv[0][1] contains the second character of that string.
So swap the indexes in your code, e.g. argv[0][4]
0
 
käµfm³d 👽Commented:
Why aren't you checking the value of argc? How would you know how many arguments were passed to your program?
0
 
Mark BullockQA Engineer IIICommented:
argc is always >= 1 the first argument is the name or pathname of the program.
0
 
ozoCommented:
If you don't pass at least 5 command line arguments to  your program, argv[5] will be undefined.

If the program name is not at least 5 characters long, argv[0][5] will be undefined.
0
 
sarabandeCommented:
I think Mark is right and you mixed up the array indices. the first index counts the pointers to char, the second index counts the characters in the argument string.

If you don't pass at least 5 command line arguments to  your program, argv[5] will be undefined.
it is not only undefined but argv[5] is an invalid pointer value - probably 0 - what causes the segmentation fault. when accessing the argv array elements you always should follow the advice kaufmed has given and check for the argc argument before accessing argv elements:

if (argc > 1)
{
       // now it is safe to use the argv[1] argument
       int len = strlen(argv[1];
       ....
}
if (argc > 2)
{
       // now it is safe to use the argv[2] argument
       std::cout << argv[2] << std::endl;
       ...
}
....

Open in new window


or

if (argc <= 3)
{
       std::cout << "program requires at least 3 arguments" << std::endl;
       return -1;
}
// here it is safe to access argv[1], argv[2], or argv[3]

Open in new window


Sara
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now