Hi there,
I just wanted to comment on something you said:
newbieg wrote: |
---|
I think this code is pretty safe |
There is one thing you should be aware of. When you allocate memory dynamically (using
new
, there is a chance that it will fail, for instance due to lack of memory. The standard version of
new
will throw an exception (std::bad_alloc). When an exception is thrown, all variables in the current scope are destructed, the problem is that pointer variables are destructed, but the memory they point to is not deallocated, so you have no more ways to access (and deallocate) that memory.
In your code:
1 2 3 4 5 6 7 8 9 10 11
|
string* hold (nullptr);
hold = new string[pos + 1];
int* bracketcount(nullptr);
bracketcount = new int[pos+1];
//...
string* indents(nullptr);
indents = new string[pos+1];
//suppose this previous line fails, the end of the function is never reached (i.e. delete[])
//so now bracketcount and hold are destroyed, but their memory is not deallocated -> leak.
|
To counteract this, there are a few possibilities:
- Don't use regular arrays, but use STL containers such as std::array, std::vector, etc. They don't require dynamic allocation and save you a lot of bother.
- Wrap all calls to
new
in a try/catch block and delete[] the pointers there. More about that here: http://cplusplus.com/doc/tutorial/exceptions/
- If you need to use pointers, use smart pointers such as std::unique_ptr and std::shared_ptr, which will automatically deallocate the associated memory when they are destructed.
Just wanted to point that out to you, as it's a rather important consideration in application security.
All the best,
NwN