Re: vsprintf in std
Jack wrote:
[...] I went over cstdio, there is a line "using ::vsprintf"
I wonder what that is... :)
What do you mean? This is probably inside namespace std and imports the
global function into that namespace. If you don't understand the syntax,
you need to get a book on C++.
My function uses malloc as the heap allocation method. :)
strTab->str[strTab->numLines] = (char *)malloc(lineSize * sizeof(char));
this buffer expands and shrinks as the program passes a new size to the
function. :)
I'd like to make it automatically managed, so that I don't have to
re-allocate the heap each time the thing is called.
This is completely different to your initial question, but anyhow:
1. sizeof (char) is by definition one, always. The C and C++ standards
require it.
2. Don't use C-style casts in C++ but rather use static_cast<> to convert
the returnvalue of malloc(). In C, don't cast it, as the conversion is
automatic.
3. Don't use manual memory management at all. In above case, use either a
std::string or use a std::vector<char>. One point is that your code doesn't
resize the buffer but it always allocates a new one, i.e. you have a memory
leak. No such things with C++ containers like vector or string. Also, you
don't have to check the returnvalue, because they use exceptions to signal
errors.
BTW: you shouldn't use vsprintf either, because it will silently write over
the end of the buffer if it needs more space than is available. Preferably
format your code using std::stringstream, which automatically increases the
size as necessary. Otherwise, vsnprintf() is also a viable method for the
time being, but make sure that you check the returnvalue and handle it
accordingly.
Of course, not using variadic functions should be your goal, because those
are inherently type-unsafe and thus dangerous. Take a look at e.g.
Boost.Format to get an idea how it can be done.
Uli