I am trying to implement a function in x86 nasm assembler which removes every n-th character from string. However, I am experiencing quite unexpected behaviour and don't really understand why it doesn't work.
// main.c
#include <stdio.h>
char *rem(char *s, int n);
int main(int argc, char *argv[])
{
char s[] = "abcabcabc";
int n = 3;
printf("%s\n", rem(s, n));
}
; rem.s
section .text
global rem
rem:
push ebp
mov ebp, esp
push esi
push edi
push ebx
mov eax, [ebp+8] ; read pointer
mov ecx, [ebp+8] ; write pointer
mov edx, [ebp+12] ; n
mov esi, 1 ; counter
loop:
cmp BYTE [eax], 0
jz fin
cmp edx, esi
jz remove
dont_remove:
; move current character to position
; pointed by the write pointer
mov edi, [eax]
mov [ecx], edi
inc ecx ; increase write pointer
inc eax ; increase read pointer
inc esi ; counter++
jmp loop
remove:
mov esi, 1 ; reset the counter
inc eax ; increase only read pointer
jmp loop
fin:
mov edi, [eax]
mov [ecx], edi
mov eax, [ebp+8]
pop ebx
pop edi
pop esi
pop ebp
ret
# Makefile
EXEFILE = main
OBJECTS = main.o rem.o
CCFMT = -m32
NASMFMT = -f elf32
CCOPT = -m32 -c
NASMOPT = -w+all
.c.o:
cc -g $(CCFMT) $(CCOPT) $<
.s.o:
nasm $(NASMFMT) $(NASMOPT) $<
$(EXEFILE): $(OBJECTS)
cc $(CCFMT) -o $(EXEFILE) $(OBJECTS)
clean:
rm *.o $(EXEFILE)
After running the code with command make && ./main I expected to see ababab (so that it removes all of the c's from "abcabcabc", in other way, removes every 3rd character). However it returns abacb. What is causing this issue? Thanks in advance for help