I took the liberty of creating some new string functions for C.
The goal with these was:
- Safety. No buffer overflows.
- If there's not enough room in the buffer to complete the operation, return the space needed.
- The ability to use C++-like strings. It supports dynamically allocated strings that will handle memory management to make sure there's enough room for operations.
- Performance. Instead of using the old C-style way of using null-terminators for getting length, it keeps track of the length itself, leading to speedups (albeit slightly more memory use).
- Slight C++-compatibility (such as constructors, destructors and an iostream overload). Nothing more.
So here is the code:
Snip: Deleted; new code below.
And now for criticism, please.
The functions can handle non-dynamic strings, in which case it will fail if no space is available. The 3rd parameter allows the caller to acquire the needed space for the operation to complete.
The strstr and strchr functions returns the position from the beginning of the string that the match was found. This is because returning a char* pointer to a dynamic string could lead to disastrous results. Therefore, to protect against mistakes, the position is returned and a char* pointer could be acquired from the original string, if required.