(e-mail address removed) said:
I am newbie ,in linux/gnu envirement,wrot test file below to see the
first argument.
#include "stdio.h"
void main (int argc, char *argv[])
{
printf ("%s", argv[0][1]);
}
After compiled it,
$ ./test ww
Segmentation fault
I have no clue to work out. help , thanks
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%s\n", argv[0]);
return 0;
}
This program could result in undefined behavior.
The C Standard says this about the function main:
-- The value of argc shall be nonnegative.
-- argv[argc] shall be a null pointer.
If argc shall be nonnegative, then 0 is an acceptable value. If argc
is 0, then argv[0] shall be a null pointer. In such a case, the printf
statement above is equivalent to:
printf("%s\n", (char*)0);
This is undefined behavior, as pointed out by some arguably
hall-of-fame members of this newsgroup in a thread that appeared over
10 years ago:
http://groups.google.com/group/comp.../16f4d84b10c041ed/c95cbfb0302763f3?lnk=st&q=#
The moral of this story is to judiciously check the value of argc
before using the value of argv in a way that could lead to undefined
behavior. For example:
#include <assert.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if ( argc > 0 )
{
printf("%s\n", argv[0]);
}
else
{
assert(argc == 0); /* must be nonnegative, so must be 0 */
printf("argc is 0.\n");
}
return 0;
}
Regards