1
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char *ptr;
    char temp[20];

    if (strlen(argv[1]) < strlen(argv[2]))
    {
        strcpy(temp,argv[1]);
        strcpy(argv[1],argv[2]);
        strcpy(argv[2],temp);
    }

    ptr = strstr(argv[1],argv[2]);
    if (ptr == NULL)
        printf("Non-inclusive");
    else
        printf("%s is part of %s", argv[2], argv[1]);
    return 0;
}

When I enter "abc abcd", I want to get "abc is part of abcd" as a result, but real result is "abc is part of abcdabc"

4
  • 2
    strcpy(argv[1],argv[2]); is not really valid. Think of argv as const char argv[] instead. Don't write to the char[]s in argv. Commented May 12, 2022 at 13:14
  • @TedLyngmo Writing to the argv strings is allowed, but writing past their end is of course not. Commented May 12, 2022 at 13:19
  • I don't understand why you can't simply do ptr = strstr(argv[2], argv[1]);. Why do you have to swap the arguments? In case you tried to make the program check if the shorter string was part of the longer string regardless of their order, then this isn't it. Commented May 12, 2022 at 13:24
  • 1
    @interjay It's allowed, but it's one of those terrible ideas we must resist. Commented May 12, 2022 at 13:28

1 Answer 1

3

The length of each string in the argv array is fixed. So when you attempt to swap the contents of argv[1] and argv[2] when their sizes are different you write past the end of the shorter one. This triggers undefined behavior.

Better to use separate char * variables, one pointing the longer string and one pointer to the shorter.

int main(int argc, char *argv[])
{
    char *ptr;
    char *s_short, *s_long;

    if (strlen(argv[1]) < strlen(argv[2])) {
        s_short = argv[1];
        s_long = argv[2];
    } else {
        s_short = argv[2];
        s_long = argv[1];
    }

    ptr = strstr(s_long,s_short);
    if (ptr == NULL)
        printf("Non-inclusive");
    else
        printf("%s is part of %s", s_short, s_long);
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.