bionio wrote: |
---|
Should I make changes to my code to allocate memory over the input argument instead of copying it to another memory location? |
I don't understand exactly. You can not reliably allocate new memory over some existing memory. (You can try with realloc, but you may not succeed.)
If you mean, should you overwrite your input, instead of allocating new buffer, you can pick any. It is like asking whether you should have + operation or += operation. Both approaches have certain uses and are broadly speaking equivalent. It is not that important in your case.
By the way, you separate words at spaces, but how do you handle consecutive spaces? Are you supposed to handle them?
Conceptual stuff aside, I think there is a leak in your code. You allocate the memory whose address you assign to ptr, but never free it. You also return pointer to ptr, but ptr is a local variable and its lifetime expires at the closing brace of strtok. So, you will return a dangling pointer. (It will probably work ok with a simple test. Those bugs manifest in complex situations.)
Indeed, it will be easier if you overwrite the input instead of copying it over to a new buffer. However, if you want to return some collection of things that you have created inside the routine, you can't do it so simply.
One way to solve this problem is to use vector instead of using arrays. They are not the same breed:
http://www.cplusplus.com/reference/stl/vector/
Another way to solve such leaks is to use auto_ptr:
http://www.cplusplus.com/reference/std/memory/auto_ptr/
And another way is to expect the caller to allocate all buffers that you need, suitably large, and pass them to your function. Those whose size you can not anticipate must be allocated with enough space in reserve to hold the maximum quantity possible. This is the C style approach.
Regards