getting segmentation fault if I dont pass any command line parameters

D

doni

Hi,

I am a beginner to C and I wrote a program that takes arguments and
prints it in hex. I am getting a segmentation fault if I dont pass any
arguments instead I want it to display the Usage message that I have.

Here is my simple program.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
char buffer[100];
char ch, * string;
int i, a=0;

if (argc < 1) {
printf("Usage: test <IPv4 Address> \n");
}
else {
string = argv[1];
strcpy(buffer, string);
a = strlen(buffer);
printf("a value is: %d", a);
for (i = 0; i < a; i++)
{
printf("Value is: %02x\n", buffer);
//printf("Value is: %X\n", buffer);
}
}
}

Thanks,
doni
 
B

Ben Pfaff

doni said:
if (argc < 1) {
printf("Usage: test <IPv4 Address> \n");
}

argc is almost always at least 1 in a hosted environment, because
argv[0] is used to contain the program's name. You should be
testing whether argc is less than 2.
 
C

CBFalconer

doni said:
Hi,

I am a beginner to C and I wrote a program that takes arguments and
prints it in hex. I am getting a segmentation fault if I dont pass any
arguments instead I want it to display the Usage message that I have.

Here is my simple program.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char * argv[])
{
char buffer[100];
char ch, * string;
int i, a=0;

if (argc < 1) {
printf("Usage: test <IPv4 Address> \n");
}
else {
string = argv[1];
strcpy(buffer, string);
a = strlen(buffer);
printf("a value is: %d", a);
for (i = 0; i < a; i++)
{
printf("Value is: %02x\n", buffer);
//printf("Value is: %X\n", buffer);
}
}
}


Try: "if (argc < 2) ...".

When printing an address (i.e. a) use the %p specifier, and cast
the address to void*.
 
D

doni

doni said:
if (argc < 1) {
printf("Usage: test <IPv4 Address> \n");
}

argc is almost always at least 1 in a hosted environment, because
argv[0] is used to contain the program's name. You should be
testing whether argc is less than 2.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p\
);}return 0;}



Thanks, Ben.

doni
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top