Re: C Style Strings
SuperKoko wrote:
Even if it is popular in C. Many C libraries use another way:
GString is a good example of a clean C interface:
http://developer.gnome.org/doc/API/glib/glib-strings.html#G-STRING-FREE
Instead of having to call "free", the user must call a library-provided
resource deallocating function.
That is necessary to prevent heap corruption if the library and the
client code use different heap managers.
If the client is written in C++ you can use boost::scoped_ptr (or
shared_ptr) with a custom deleter that calls the deallocating function
when appropriate. So you can add your own RAII.
I am not totally against libraries allocating resource that require to
be freed, but if they do so it should be obvious. For example, a
library will often provide a class factory. If I ever have my libraries
create anything in this way, the function name always begins with (or
is called) create.
Using internally, functions which use with the any range of
user-provided memory (or iterators) is a good way to reuse efficiently
code.
However, in C, as in C++, it is good to encapsulate things and to
provide comfortable interfaces.
However when a library is written in C it is often written for
relatively low-level programming. Often a function will require you to
provide a buffer and its length. It will never overwrite the buffer but
will often flag you if the buffer you provided was inadequate. And
sometimes you can request ahead (at little cost) how big your buffer
needs to be.
C also has that wonderful technique of sticking a variable-length
buffer at the end of a structure thus:
struct some_type
{
header_info header;
char data[1];
};
but you malloc sizeof( header_info ) + actual_data_size (or safer
sizeof( some_type ) + data_size - 1 );
and then later on you call a "free" on the whole thing. It means that
you only have one "malloc" for everything. Beware that such a struct
cannot be safely copied though! (well if you do it will be sliced).