在没有标准库的情况下计算程序集x86中的单词

时间:2016-01-06 17:31:58

标签: assembly x86

我试图在x86程序集中编写简单的代码来计算字符串中的单词数但不使用标准库(在GCC中使用addAll选项)。例如,如果字符串看起来像这样:-nostdlib 我的程序应该写aaa ab cccc c作为输出。这意味着检查下一个字符是否是空格是不够的,但我不知道我应该如何处理这个任务。你能帮帮我吗?

然而,我试图检查那些空间。我写了我的代码:

4

但是节目仍在给我"核心倾销"错误,我不知道为什么会这样。有人可以向我解释一下吗?

2 个答案:

答案 0 :(得分:0)

好吧,我不确定你是否指定它,但你可以将C标准库链接到你的应用程序并调用strtok()并计算它在循环中返回的非NULL指针的总数。

p = strtok(str,delimeters);
while (p != null) {
    words++; p = strtok(NULL,delimeters);
}

mov  words, 0
push delimeters
push str
call strtok
add  esp, 8
cmp  eax, 0
je   done

doAgain:
inc  words
push delimeters
push 0
call strtok
add  esp, 8
cmp  eax, 0
jne  doAgain

done:

答案 1 :(得分:0)

我了解了一个调试选项,它真正帮助我理解我做错了什么。通过一些外部帮助,我完成了这项任务。它不是我见过的最好看的代码,但它有效。

我要感谢大家的帮助,我真的很感激。对于我在创建这个问题时犯的所有错误,我也很抱歉。我会尽量不做同样的错误两次。

这是我的解决方案(我稍微改了一下。现在用户输入一个字符串来编程):

.intel_syntax noprefix
.text
.globl _start

_start:
  mov eax, 3
  mov ebx, 0
  mov ecx, offset msg
  mov edx, 100                # maximum number of characters
  int 0x80

  xor ebx, ebx                # counter of words

_loop:
  mov al, [ecx]               
  cmp al, 10                  # 10 is the end of a string
  je intToString
  cmp al, ' '                 
  jne word                    # if it's not a space, it's a beginning of the word
  inc ecx
  jmp _loop

word:
  inc ecx
  mov al, [ecx]
  cmp al, 10                  
  je wordadd                  # case when string ends with space
  cmp al, ' '                 
  jne word                   # if the next characters is a space, it means that it's the end of a word
  inc ecx
  inc ebx                     
  jmp _loop

intToString10:                # changing the counter int to string (case when it's bigger than 10)
  mov eax, ecx                # By dividing number by 10 I split the number (the result is quotient and remainder)
  mov dl, 10                  # which I then put in the right order to buffer
  div dl
  add al, '0'                 # changing number to string by adding a 0 at the end
  mov edx, offset buffer       
  mov [edx], al               
  add ah, '0'                 
  inc edx
  mov [edx], ah
  jmp end

wordadd:                     # case when the whole string ends with space
  inc ebx                     

intToString:                 # changing int to string (case when it's smaller than 10)
  mov ecx, ebx
  cmp ecx, 10                 
  jae intToString10
  add ecx, '0'                
  mov [buffer], ecx            

end:
  mov eax, 4
  mov ebx, 1
  mov ecx, offset buffer
  mov edx, 5                  
  int 0x80

mov eax, 1                  
mov ebx, 0
int 0x80

.data

buffer:
  .ascii "    \n"            

msg:
  .skip 100