I am using strcmp in following ways
Passing pointers to string literals but, the second result in seg fault. even though i have confirmed that pointers point to correct string literals, i am confused as to why i am getting seg fault.. Here is the code:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *args[])
{
char firstName[strlen(*++args)];
strcpy(firstName, *args);
char lastName[strlen(*++args)];
strcpy(lastName, *args);
printf("%s\t%s\n", firstName, lastName);
printf("%d\n", strcmp(firstName, lastName));// this works
printf("%d\n", strcmp(*(--args),*(++args)));//this gives me a seg fault
return EXIT_SUCCESS;
}
I am saving it as str.c and when i compile it, first i get following warning:
[Neutron@Discovery examples]$ gcc -Wall str.c -o str
str.c: In function ‘main’:
str.c:15: warning: operation on ‘args’ may be undefined
finally running it, gives a seg fault as shown below
[Neutron@Discovery examples]$ ./str Jimmy Neutron
Jimmy Neutron
-4
Segmentation fault (core dumped)
Because of code if (strcmp (argv [2], NULL) == 0), you are passing NULL as string pointer to strcmp () function; that try to deference at NULL to compare chars codes (e.g. acsii code) this cause undefined behavior at run time. You should compare a string pointer with NULL using == as if (argv [2] == NULL)
Why segmentation fault? Because of code if(strcmp(argv, NULL) == 0), you are passing NULL as string pointer to strcmp()function; that try to deference at NULL to compare chars codes (e.g. acsii code) this cause undefined behavior at run time. You should compare a string pointer with NULL using ==as if(argv == NULL)
You can't use strcmp () to compare to NULL. Neither argument can be null. In this situation it doesn't make sense anyway. If the argument isn't present, argc will be < 3, and if it is somehow empty it will be zero length.
Don't use --
and ++
when you pass the same variable to the same function twice as two different parameters.
Instead of printf("%d\n", strcmp(*(--args),*(++args)));
do
char *first = *(--args);
char *second = *(++args);
printf("%d\n", strcmp(first,second));
Still not really readable (better use indexes and check against argc
for validity), but at least you don't change the value and evaluate multiple times it at the same sequence point.
In addition to what littleadv's post says, your buffers are one character too short (it didn't leave any space for the null-terminator). Thus, your strcpy
causes a buffer overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With