I am getting a segmentation fault for some reason, I wrote this program that calculates the days between two dates and wanted to get the "dd-mm-yyyy" to be represented as a string and "dd2-mm2-yyyy2"should also be represented as a string, i thought I could solve it this way, but i cam getting a segmentation fault, can someone help me? what am i doing wrong?
1 Answers
This seems incorrect. argv[1] is your "day" string, which is 1 or 2 characters long, and you're indexing characters 3 and 4.
char monstr[3];
monstr[0]= argv [1][3];
monstr[1]=argv [1][4];
monstr[2] = '\0';
This should probably be:
char monstr[3];
monstr[0]= argv [2][0];
monstr[1]=argv [2][1];
monstr[2] = '\0';
Same with some other strings.
But, that said, I'm basing this on how you seem to be parsing input. If you want your input to be dd-mm-yyyy, then you're not getting input right. Instead, you should do something like this:
int dd, mm, yyyy;
sscanf(argv[1], "%d-%d-%d", &dd, &mm, &yyyy);
And same with the other string. And in that case, the previous thing I corrected doesn't need to be corrected.
As a general piece of advice: the reason segmentation faults happen is because you're accessing memory that you aren't able to access. A common cause of this is going outside of array bounds, or using invalid pointers. In your case, it seems like one of those two, and it comes from misuse of argv.

- 492
- 3
- 11
-
This question seems to already be answered by [date-time conversion](https://stackoverflow.com/questions/95492/how-do-i-convert-a-date-time-to-epoch-time-unix-time-seconds-since-1970-in-per) – user3629249 Sep 20 '19 at 22:57
-
so is it going to be like this? char daystr[3]; daystr[0] =argv[1][0]; daystr[1] = argv[1][1]; daystr[2] = '\0'; dd = atoi(daystr); char monstr[3]; monstr[0]= argv [2][0]; monstr[1]=argv [2][1]; monstr[2] = '\0'; mm = atoi(monstr); char yearstr[5]; yearstr[0]= argv [3][0]; yearstr[1]=argv [3][1]; yearstr[2]= '\0'; yyyy = atoi(yearstr); char daystr2[3]; daystr2[0] =argv[4][0]; daystr2[1] = argv[4][1]; daystr2[2] = '\0'; dd2= atoi(daystr2); – Sep 24 '19 at 00:21
\n", argv[0] );`
– user3629249 Sep 20 '19 at 22:28