semut said:
Given that the string is of null-terminated type. What could be the
possible causes (by experience) the string to have no null character
(\0)
and cause buffer overflow later.
None. If it doesn't have a null character terminating it, it isn't a string.
When you choose to use a particular data format, it is your responsibility
to ensure that the requirements of that format are met. For example, if you
choose to use a binary search tree, it is your responsibility to ensure
that the tree remains ordered whenever you add, remove, or move nodes. If
you fail to do this, you don't *have* a binary search tree. If you choose
to use a double-linked list, it is your responsibility to ensure that every
node points to its previous node (or NULL if there isn't a previous node)
and its next node (or NULL if there isn't a next node). If you fail to do
this, you don't *have* a double-linked list.
With strings, the requirements are much gentler - all you have to do is
ensure that you don't exceed your memory availability and that you have a
null terminator at the end of the data, taking care to replace it if it
gets erased for some reason (as it might, when copying substrings about or
getting your hands dirty with pointers). But if you fail to do this, you
don't *have* a string.
How many different ways are there to foul up a binary search tree?
Infinitely many. But they all have one shared characteristic: they break
the binary search tree model. How many different ways are there to foul up
a double-linked list? Infinitely many. But they all have one shared
characteristic: they break the double-inked list model.
And how many different ways are there to foul up a string? Infinitely many.
But they all have one shared characteristic: they break the string model.
So the answer is simple: don't break the model.
I know it is quite broad, just like to
find out the causes as much as possible so that I could impose stricter
checking toward my codes.
When writing to a string:
1) Always know your bounds.
2) Never write outside your bounds.
3) Ensure the string is null-terminated before you give up control over it.
note: I could not use std::string cause it will require a total
rewrite.
std::string is just a syntax error, so I don't see how it is relevant.