okay, this is a problem that has been bugging me for a while now, and as almost everytime I use a function from string.h I encounter it, it's time for me to get this clear.
I don't know where I've picked it up, most likely from reading open source, but it's become a habit. my intentions by doing it is for safety, to ensure that the string passed will always include a terminating null. but after reading a little about buffer overflows, I'm not exactly sure if this is a good habit. this is the kind of stuff that I'm talking about:
now, after reading the description for strncpy, I see that this is okay:Code:strncpy(dest, source, sizeof dest - 1);
the "sizeof dest - 1" will ensure that the number of characters copied from source will always be shorter than dest, and that there will always be room for 1 terminating null character in the case of any truncation of source (assuming that dest is initialized with null).No null-character is implicitly appended to the end of destination, so destination will only be null-terminated if the length of the C string in source is less than num.
now, lets take a look at another function from string.h, where this is not so clear:
same parameters, different function.Code:strncat(dest, source, sizeof dest - 1);
that would mean that the "sizeof dest - 1" is still correct, right?Appends the first num characters of source to destination, plus a terminating null-character. If the length of the C string in source is less than num, only the content up to the terminating null-character is copied.
I just want to make sure that I'm getting this right, as a lot of the descriptions at MSDN for Win32 API functions are rather vague when it comes to preparing for null terminators. I just want to make sure that the programs I'm writing aren't riddled with buffer overflow vulnerabilities as a result of this "- 1" habit.
could anyone please tell me if everything I've shown as an example here is correct, and when I should not be using - 1?
this is a rather newbie question, but it's got me paranoid, everytime I write - 1 I'm worrying if I am just setting myself up for buffer overflows. if anyone could clear this up for me, it would be greatly appreciated.
thank you in advance.