c - strcasecmp 实现不打印

标签 c assembly gdb x86-64

我正在开发一个小项目,我必须从 C 库重新编码一个函数。实际上我正在开发 strcasecmp:

BITS 64

%include "minilib.inc"

section .text

my_strcasecmp:
init:
    mov r10b, [rdi]
    mov r11b, [rsi]
    jmp while

while:
    cmp r10b, 0
    je end
    cmp r11b, 0
    je end
    cmp r10b, 90
    jle checkfirstup
    cmp r11b, 90
    jle checksecondup
    jmp strcasecmp

strcasecmp:
    cmp r10b, r11b
    jne end
    inc rdi
    inc rsi
    jmp init

checkfirstup:
    cmp r10b, 65
    jge r10btolowcase
    jmp checksecondup

r10btolowcase:
    add r10b, 32
    jmp while

checksecondup:
    cmp r11b, 65
    jge r11btolowcase
    jmp strcasecmp

r11btolowcase:
    add r11b, 32
    jmp while

end:
    movzx rax, r10b
    movzx rbx, r11b
    sub rax, rbx
    ret

这是 c 中的代码:

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

extern int my_strcasecmp(const char *string1, const char *string2); /* Prototype */

int main(void)
{
    char *str1 = "S";
    char *str2 = "S";
    int result;

    result = strcasecmp(str1, str2);

    if (result == 0)
        printf("Strings compared equal.\n");
    else if (result < 0)
        printf("\"%s\" is less than \"%s\".\n", str1, str2);
    else
        printf("\"%s\" is greater than \"%s\".\n", str1, str2);

    return 0;}

当我尝试 strcasecmp 时,我总是说“nanana 大于 nanana”,但我不明白为什么。

我该如何解决这个问题?

最佳答案

问题是,当第一个字符不在 [A,Z] 中时,您会立即跳转到 checksecondup ,您只检查第二个字符的下限。那时 cmp r11b, 90 从未执行过! (它会触发不需要的add r11b, 32。)

解决方案是独立地对两个字符进行 Lase:

  ...
  cmp r10b, 65
  jb  Next
  cmp r10b, 90
  ja  Next
  add r10b, 32
Next:
  cmp r11b, 65
  jb  Next_
  cmp r11b, 90
  ja  Next_
  add r11b, 32
Next_:
  cmp r10b, r11b
  ...

关于c - strcasecmp 实现不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71288607/

相关文章:

c - 如何获取 const char 指针的大小

c - 获取 float 的指数

generics - 如何用汇编语言表示泛型类型

c++ - gdb 打印 : const set<Int4> & var_name 的内容

c - "Detaching after fork from child process 15***"的含义?

c - 在c中返回指针的函数(int?)

arrays - 数组中元素出现的频率

assembly - QASM 中的量子计算模拟

c - 在 C 中,确保多段代码的汇编指令数是固定的

c++ - 如何让 GDB 在每次系统或库函数调用时中断?