ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
strcmp compares two strings and gives the output ..
but if we fill one string with all 0s then the output is allways 0.ie both the strings are same.
why is his happening
Code:
#include <stdio.h>
#include <string.h>
int main (int argc,char *argv[])
{
char szInput[3];
int flag=0;
memset(szInput,0,sizeof(szInput));
strcpy(szInput, argv[1]);
if( strcmp(szInput, "a")== 0){
flag =1;
}
if (flag){
printf("correct");
}
else
printf("incorrect ");
return 0;
}
You declared a buffer of size 3; then stuffed input of "0000\0" into that buffer. strcpy() will copy up to the terminating null-character. Thus szInput will have "0000" -- note that there is not a terminating null in that buffer because you have exhausted all the space, and in fact have overrun the buffer space, perhaps even overwriting the value of 'flag' which sits on the stack right after szInput.
Anyhow, I'm not sure how you got your result; perhaps you should fix your code or adjust how much input (say at most two character) you provide from the command line.
P.S. '0' and \0 are not the same. The former is the character zero, whose ASCII value is 48. The latter is a NUL character, whose ASCII value is 0.
P.S. #2 Never use strcpy(); use strncpy() instead. Similarly, don't use gets(), sprintf(), or any other library function where you cannot specify the length of the destination buffer.
Last edited by dwhitney67; 08-23-2012 at 05:29 AM.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.