I need to pas two command line arguments and I tried the following:
#include <stdio.h>
#include <stdlib.h>
void power(int base, int exp){
int res=1;
while(exp!=0){
res *= base;
--exp;
}
printf("Res = %d",res);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage %s arg2 arg2\n(EG: %s 2 3)\n",argv[0],argv[0]);
exit(1);
}else{
power(atoi(argv[1]),atoi(argv[2]));
}
printf("\n");
return 0;
}
Output:
michi@michi-laptop:~$ ./power Usage ./power arg2 arg2 (EG: ./power 2 3) michi@michi-laptop:~$ ./power 2 3 Res = 8
Everything until here is ok, but if when save argv[1] and argv[2] in variable like this:
int base = atoi(argv[1]);
int exp = atoi(argv[2]);
I get Segmentation fault
code:
#include <stdio.h>
#include <stdlib.h>
void power(int base, int exp){
int res=1;
while(exp!=0){
res *= base;
--exp;
}
printf("Res = %d",res);
}
int main(int argc, char *argv[]) {
int base = atoi(argv[1]);
int exp = atoi(argv[2]);
if (argc != 3) {
printf("Usage %s arg2 arg2\n(EG: %s 2 3)\n",argv[0],argv[0]);
exit(1);
}else{
power(base, exp);
}
printf("\n");
return 0;
}
But when I use Atoi inside printf everything is OK:
#include <stdio.h>
#include <stdlib.h>
void power(int base, int exp){
int res=1;
while(exp!=0){
res *= base;
--exp;
}
printf("Res = %d",res);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage %s arg2 arg2\n(EG: %s 2 3)\n",argv[0],argv[0]);
exit(1);
}else{
power(atoi(argv[1]), atoi(argv[2]));
}
printf("\n");
return 0;
}
My question is:
is this issue happen because of Atoi?
is this issue happen because I try to access argv[1] and argv[2] and they are not exists when I type ./program?
If I type ./program 2 3 everything is ok, which makes me think that segmentation fault happens because I try to access a memory location which doesn't belong to me at that point.