Author Topic: Heap Space Allocation for enhanced strcat  (Read 7185 times)

Offline aVoX

  • Jr. Member
  • *
  • Posts: 13
Heap Space Allocation for enhanced strcat
« 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.

Offline Frank Kotler

  • NASM Developer
  • Hero Member
  • *****
  • Posts: 2667
  • Country: us
Re: Heap Space Allocation for enhanced strcat
« Reply #1 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


Offline aVoX

  • Jr. Member
  • *
  • Posts: 13
Re: Heap Space Allocation for enhanced strcat
« Reply #2 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...

Offline Rob Neff

  • Forum Moderator
  • Full Member
  • *****
  • Posts: 429
  • Country: us
Re: Heap Space Allocation for enhanced strcat
« Reply #3 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