Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第5章的strcmp实现有点小问题&修改建议 #10

Closed
UKeeySDis opened this issue Apr 7, 2017 · 3 comments
Closed

第5章的strcmp实现有点小问题&修改建议 #10

UKeeySDis opened this issue Apr 7, 2017 · 3 comments

Comments

@UKeeySDis
Copy link

源代码libs/string.c中实现strcmp函数时的源代码是:

inline int strcmp(const char *str1, const char *str2)
{
    while (*str1 && *str2 && (*str1++ == *str2++))
    ;
    if (*str1 == '\0' && *str2 == '\0') {
           return 0;
    }

    if (*str1 == '\0') {
      return -1;
    }
    return 1;
}

这样如果两个字符串长度相等但字符串不同时,检测出来的结果就不对,大神应该当时没有注意到,算是一个小瑕疵吧。修正代码:

inline int strcmp(const char *str1, const char *str2)
{
    while(*str1 == *str2)
    {
	    if(*str1 == '\0')
		    return 0;
	    str1++;
	    str2++;
    }
    return *str1 - *str2;
}

同时感谢大神的文档,比看《Orange's 一个操作系统的实现》要简易很多。

@hurley25
Copy link
Owner

hurley25 commented Apr 8, 2017

有没有测试的case呢?具体传入什么字符串会导致返回0呢?

@UKeeySDis
Copy link
Author

如果两个字符串的长度和字符都相等才会返回0。比如字符串str1="test a"和字符串str2="test b",按照之前的源码当判断到两个字符串最后的字符ab时,由于不相等会出while循环,但是代码中进行了++操作,就直接到达两个字符串的结束符位置了,然后会进if(*str1 == '\0' && *str2 == '\0'这个条件,返回0,但是其实这两个字符串虽然长度相同但并不相等。
测试代码(调用了库中的strcmp做比较):

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

int my_strcmp(const char *str1, const char *str2)
{
    while (*str1 && *str2 && (*str1++ == *str2++))
	    ;
    if (*str1 == '\0' && *str2 == '\0') {
	    return 0;
    }

    if (*str1 == '\0') {
	    return -1;
    }
    return 1;
}

int main()
{
    char *str1 = "test a";
    char *str2 = "test b";

    printf("%d\n", my_strcmp(str1, str2));
    printf("%d\n", strcmp(str1, str2));

    return 0;

}

@hurley25
Copy link
Owner

hurley25 commented Apr 9, 2017

嗯, 是的,这个函数是有问题的。多谢指出问题,已经修复并提交。
同时字符串函数移动到头文件里了(inline函数放在.c里好奇怪,不知道当时从哪里来的代码)。

@hurley25 hurley25 closed this as completed Apr 9, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants