NASM - The Netwide Assembler

NASM Forum => Programming with NASM => Topic started by: aVoX on November 12, 2011, 03:13:45 PM

Title: Heap Space Allocation for enhanced strcat
Post by: aVoX on November 12, 2011, 03:13:45 PM
Hello!
I wanted to create an alternative implementation of strcat. Instead of passing 2 strings by-ref and sticking one on the end of the other one, I want to create a new string that is returned, once the concatenation is done.
In C that would be easy as apple pie:
Code: [Select]
char *my_strcat( char *str1, char *str2 )
{                     
    int i, j;
    char *res = (char *) malloc( strlen(str1) + strlen(str2) + 1 );

    for ( i = 0; str1[i]; res[i] = str1[i++] ) ;
    j = i;
    for ( i = 0; str2[i]; res[j++] = str2[i++] );
    res[j] = '\0';
    return res;
}
Is something like this also possible in assembly, without a call to malloc/HeapAlloc/whatsoever?

Thanks in advance, aVoX.
Title: Re: Heap Space Allocation for enhanced strcat
Post by: Frank Kotler on November 12, 2011, 08:29:32 PM
I don't see how. The only reason it's "easy as pie" in C is that someone has already baked the pie. We can use malloc(), or implement our own. I'd check to make sure malloc() succeeds before going ahead and using it! C's strcat() looks a little "dangerous" to me - what guarantee do we have that there's really enough room in "dest"? I like your method better, but do make sure that malloc() (C's or your own) succeeds!

Best,
Frank

Title: Re: Heap Space Allocation for enhanced strcat
Post by: aVoX on November 13, 2011, 01:38:02 PM
Ok, I found out that both, malloc and C++'s new operator call HeapAlloc (btw I didn't know that the msvcrt was open source :o check out <VSPath>\VC\crt\src). But there's also a disadvantage: Everytime I call my_strcat I have to do a HeapFree sooneror later...
Title: Re: Heap Space Allocation for enhanced strcat
Post by: Rob Neff on November 13, 2011, 03:17:42 PM
Freeing memory at the appropriate time is vital to long running processes.  Taking advantage of C++ can hide some of the lower level details such as memory deallocation during object destruction.

For implementing a custom strcat safely without involving malloc in your routine an alternative might be to do something like the following:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms647518(v=vs.85).aspx (http://msdn.microsoft.com/en-us/library/windows/desktop/ms647518(v=vs.85).aspx)