Memory Leak when combining char arrays

I have a function to combine two char arrays but it results in a memory leak.
1
2
3
4
5
6
7
8
const char* combine(const char* first,const char* second)
{
    char* buffer = new char[256];
    strcpy(buffer,first);
    strcat(buffer,second);

    return buffer;
}


Any better way to go about this?
The returned value has to be a char pointer.
Thanks in advance.
buffer should be initialized to an array of length >= strlen(first) + strlen(second) + 1.
The return type for the function should be a pointer to non-const: char *.
So:
1
2
3
4
5
6
7
8
char* combine(const char* first,const char* second)
{
    char* buffer = new char[strlen(first) + strlen(second) + 1];
    strcpy(buffer,first);
    strcat(buffer,second);

    return buffer;
}

Thanks, ill try it.
It only results in a memory leak, if your calling code doesn't delete the allocated memory buffer. This is part of the contract of your function - that it will allocate memory, and hand the ownership of that memory to the calling code.

If this is C++ code, then you can make this explicit by having the function return a std::unique_ptr, rather than a raw C-style pointer.

If this is C code - which it looks like, because you're using C library calls - then you'll have to ensure the calling code deletes the memory itself.

The alternative is to have the function take, as an argument, the buffer that will be filled with the result. This is the approach a lot of C libraries take in their API, e.g. the Win32 library.
Last edited on
Topic archived. No new replies allowed.