There is no memory leak.
You seem to be confused, though, about how heap allocation works. There is only one chunk of memory being allocated here, and it is not "local" to either halfString()
or to main()
. The allocated chunk exists in the heap, and is not scoped to a particular code block.
malloc()
returns a pointer to it. You then return that pointer back to main()
, but the value of the pointer is still the same: it points to the same address in memory, the same chunk of heap. main()
then properly frees it.
As a design consideration, this is often not the best thing to do. In general, a caller may not necessarily know that the pointer returned by halfString()
points to a chunk that was allocated with malloc()
and that they need to free()
it. This would have to be very clearly and carefully documented. A better solution might be to provide a freeHalfString()
function which does the freeing; then from a maintenance standpoint, those two functions can be put in the same place and maintained concurrently, so that the caller doesn't need to worry about how the buffer was allocated, or how to free it.
(As others have pointed out, you also have a buffer overflow because you need to allocate strlen(input) + 1
bytes to include the NULL terminator.)