Here is my program:
--------------------------------------...
#include<stdio.h>
int main(int argc, char *argv[])
{
char Buffer[10];
if(argc < 2)
{
printf("Put an option\n");
exit(1);
}
strncpy(Buffer,argv[1],9);
if(!strcmp(Buffer,"?random"))
printf("They want help\n");
else if (!strcmp(Buffer,"/A"))
printf("Option\n");
else if (!strcmp(Buffer, "/B"))
printf("BBBBBBBBBBB\n");
else
printf("WRONG\n");
}
--------------------------------------...
lets say the file name elseif.c
After compiling, i can say this program works. However if i change it to:
--------------------------------------...
#include<stdio.h>
int main(int argc, char *argv[])
{
char Buffer[10];
if(argc < 2)
{
printf("Put an option\n");
exit(1);
}
//changed argv[1] to argv[2]
strncpy(Buffer,argv[2],9);
if(!strcmp(Buffer,"?random"))
printf("They want help\n");
else if (!strcmp(Buffer,"/A"))
printf("Option\n");
else if (!strcmp(Buffer, "/B"))
printf("BBBBBBBBBBB\n");
else
printf("WRONG\n");
}
It compiles, but when i execute i get message says
Segmentation fault
Can you please explain to me why this happens?
Im new to C, i try to play with codes to see how it works...
Tags: