Check if argv is valid before accessing it:
int len = strlen(argv[1]);
if(argc != 2 )
If argc != 2
evaluates to true
, then argv[1]
would be a NULL
pointer (assuming argc
is 1).
Check if the arguments are valid before you try to access them, else your program could dereference a NULL
pointer and exhibit undefined behaviour.
if (argc != 2) {
/* print usage message here.. */
return EXIT_FAILURE;
}
strlen() returns a size_t:
Note that strlen()
returns a size_t
, not an int
. Do not mismatch numeric types.
Error messages should go to stderr:
Error messages deserve to be printed to stderr
, not stdout
.
fprintf(stderr, "Usage:./substitution\n
Or as formatted output is not required here, simply:
fputs ("Usage:./substitution\n", stderr);
See also: Why use stderr when printf works fine?