LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   confusion with concepts of strcmp in c language (https://www.linuxquestions.org/questions/programming-9/confusion-with-concepts-of-strcmp-in-c-language-4175423569/)

batman4 08-23-2012 05:09 AM

confusion with concepts of strcmp in c language
 
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;
    }

if the output is ./a.out 0000
it gives correct

dwhitney67 08-23-2012 05:25 AM

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.

NevemTeve 08-23-2012 05:30 AM

You merrily overwrite your stack with the strcpy, so the results are unpredictable. Fix:

Code:

#include <stdio.h>
#include <string.h>

int main (int argc,char *argv[])
{
    const char *szInput;

    if (argc<2) {
        printf ("give param\n");
        return 0;
    }
    szInput= argv[1];

    if (strcmp (szInput, "a")== 0) {
        printf ("\"%s\" equal to \"a\"\n", szInput);
    } else {
        printf ("\"%s\" not equal to \"a\"\n", szInput);
    }
    return 0;
}


KernelJay 09-27-2012 07:33 PM

For some additional insight into why strcpy is so dangerous, check out my latest blog post on the subject:
VERT Vuln School: Stack Buffer Overflows 101

Part 1: Introducing the Bug
Part 2: Explaining the Stack
Part 3: Exploiting the Bug

Thanks,
Craig


All times are GMT -5. The time now is 09:55 PM.