Concat two strings in C and allocate dynamically buffer

大城市里の小女人 提交于 2019-12-25 07:30:58

问题


I know this kind of question has already been asked. I also used the solution of this topic to my tests. However, I want to know how using this kind of function without memory leak neither exception.

Note: LPTSTR ~ char* and LPCTSTR ~ const char*

void add_to_buffer(LPTSTR* buffer, LPCTSTR msg) {
    // Determine new size
    int newSize = 0;

    // Allocate new buffer
    if (*buffer == NULL)
        newSize =  _tcsclen(msg) + 1; // strlen()
    else
        newSize = _tcslen(*buffer) + _tcsclen(msg) + 1;

    LPTSTR newBuffer = (LPTSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, newSize); // malloc()

    // Do the copy and concat
    if (*buffer == NULL)
        _tcscpy(newBuffer, msg); // strcpy()
    else
    {
        _tcscpy(newBuffer, *buffer);
        _tcscat(newBuffer, msg); // strcat()
        // release old buffer
        HeapFree(GetProcessHeap(), 0, *buffer); // free()
    }

    // store new pointer
    *buffer = newBuffer;
}

Tests:

LPTSTR test = NULL;
add_to_buffer(&test, _T("User:\r\n"));
add_to_buffer(&test, _T("42"));

First call to add_to_buffer works. However, the second function call causes an exception at HeapFree. I'm sure this is a problem about pointers, but I do not understand how to fix it.

Is it a good method? How to fix my exception?


回答1:


If you are compiling the code as multi-byte application this line

LPTSTR newBuffer = (LPTSTR)HeapAlloc(
  GetProcessHeap(), 
  HEAP_ZERO_MEMORY, 
  newSize
); 

might allocate to few memory.

To fix this use:

LPTSTR newBuffer = (LPTSTR)HeapAlloc(
  GetProcessHeap(), 
  HEAP_ZERO_MEMORY, 
  newSize * sizeof(*newBuffer)
); 

Besides this and the fact that the code lacks error checking for system calls the code looks fine.

However, to simplify things one can use HeapReAlloc() instead of the combination of HeapAlloc() and HeapFree().

If the program crashes anyway this might due to the memory management already being mashed up before this actual crash you observe.




回答2:


If your program is unicode-enabled, you're not allocating enough memory - because string length (in symbols) and string size (in bytes) don't match.

If it isn't, I don't see reason of using non-standard-C types over standard ones. It shouldn't be a problem though.



来源:https://stackoverflow.com/questions/24263692/concat-two-strings-in-c-and-allocate-dynamically-buffer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!