Feedback on design implementation of a alloc/strncpy
From: Perry S. Morris (relvinian_at_mindspring.com)
Date: 04/24/04
- Next message: noob2asm: "make a 3 spinning cube"
- Previous message: Frank Kotler: "Re: CALL too posision"
- Next in thread: Perry S. Morris: "Re: Feedback on design implementation of a alloc/strncpy"
- Reply: Perry S. Morris: "Re: Feedback on design implementation of a alloc/strncpy"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 24 Apr 2004 17:32:29 +0000 (UTC)
Hello,
I had a routine in c/c++ that allocated a buffer and copied a non-null
terminated string into it and terminated it. I have re-written it in
assembly using MASM 6.15 (mainly to help me learn assembly better then I do)
and looking for feedback on ways I can write better ASM code. Here is my
full function. Also, this function will allocate the buffer with the size
in four-byte alignments.
;--------------------------------------------------------------
;prototype:
;void __stdcall StrNCopy(char** pDest, char* pSrc, int len);
;--------------------------------------------------------------
;example usage:
;char* pszString = NULL;
;StrNCopy(&pszString, pBuffer, nLen);
; do something with pszString;
;if (pszString)
; free(pszString);
--------------------------------------------------------------
title "StrNCopy.asm"
.586
.model flat
extrn __imp__malloc:near ; malloc()
.data
align 8
_TEXT SEGMENT
_pDest$ = 8
_pSrc$ = 12
_nLen$ = 16
_TEXT ENDS
.code
_StrNCopy@12 proc near
push ebp
mov ebp, esp
push ebx
push esi
push edi
; get the source buffer into ESI
mov esi, dword ptr _pSrc$[ebp]
; align the outgoing buffer length on a four-byte boundary.
; we also need to make room for the NULL terminator
mov ebx, dword ptr _nLen$[ebp] ; need to remember len!
xor edx, edx
lea ecx, dword ptr [ebx+1]
; aee if we are already aligned
and ecx, 3
je short @Aligned
; we aren't so align it now
mov edx, 4
sub edx, ecx
@Aligned:
; remember new length
lea eax, dword ptr [ebx+1+edx]
; allocate the new buffer
push eax
call dword ptr __imp__malloc
pop ecx
; see if we have a successfull allocation
test eax, eax
je short @Done
; copy the string
mov edi, eax
shr ecx, 2
rep movsd
; terminate our string
mov byte ptr [eax+ebx], cl
; set the outgoing buffer ptr to the new string
mov edi, dword ptr _pDest$[ebp]
mov dword ptr [edi], eax
@Done:
pop ebx
pop edi
pop esi
pop ebp
ret 12
_StrNCopy@12 ENDP
end
--------------------------------------------------------------
Thank you
- Next message: noob2asm: "make a 3 spinning cube"
- Previous message: Frank Kotler: "Re: CALL too posision"
- Next in thread: Perry S. Morris: "Re: Feedback on design implementation of a alloc/strncpy"
- Reply: Perry S. Morris: "Re: Feedback on design implementation of a alloc/strncpy"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|