开发者

'Segmentation Fault' while recoding memset

开发者 https://www.devze.com 2023-02-18 23:30 出处:网络
I started ASM a few days ago and started recoding all the simple function libc offers us like strlen, strchr or memset. I didn\'t have any problem until I tried recoding memset.

I started ASM a few days ago and started recoding all the simple function libc offers us like strlen, strchr or memset. I didn't have any problem until I tried recoding memset.

Here is the prototype of the C function:

void *memset(void *s, int c, size_t n);

Here is my ASM code:

[BITS 32]

global my_memset

my_memset:
    push    ebp
    mov     ebp, esp

    mov     eax, [ebp+8]
    mov     edx, [ebp+12]
    mov     ecx, [ebp+16]

myloop:
    mov     [eax], edx
    add     eax, 1
    loop    myloop

endfunc:
    mov     eax, [ebp+8]
    leave
    ret

And this is the main I use for my test

#include <stdio.h>

void *my_memset(void *s, int c开发者_如何学C, size_t n);

void main(void)
{
  char test[] = "thisisatest";

  printf("%s\n", test);
  my_memset(test, 'b', 5);
  printf("%s\n", test);
}

I am a bit lost on the use registers, so if I did any big mistake please let me know.

[EDIT] Main problem has been solved(no more segfaults or errors). But I still have one last -small- problem. The string I receive is 'bbbbb' when it should be 'bbbbbsatest'

Thank you, Ephismen.


Are you possibly using a string literal as the target for your memset? In that case, [EAX] aka *s, can point to read-only memory.

Edit:
Assuming testand toto are the same variable, it should really be const char* test= becase a string literal is read-only. Try char test[] = instead to create an array containign a copy of the literal.

Edit2:
I have a javascript problem today, so I can not add comments.

Anyway, the new problem is mov [eax],edx which stores 4 bytes (some of which are 0). The previous store move [eax],dl stored 1 byte at a time.

Edit3:
@stupid_idiot - I first wrote that edx is 2 bytes (confused it with dx), and fixed that before seing your comment. Honest! :-)


I think you want to:

mov [eax], dl

This moves the value in the dl register to the memory address indicated by eax.

0

精彩评论

暂无评论...
验证码 换一张
取 消