The above string functions all depend on the survival of a null terminator at the end of a string. This isn't forever a secure think. Besides, some of them, obviously strcat, depend on the fact that the purpose string can hold the complete string being appended onto the end. Even though it may seem like you'll not at all make that sort of mistake, historically, problems based on by chance writing off the end of an array in a function like strcat, have been a main trouble.
Luckily, in their never-ending knowledge, the designers of C have integrated functions intended to help you keep away from these issues. Alike to the method that fgets takes the utmost number of characters that fit into the buffer; there are string functions that take an extra argument to specify the length of the target buffer. Such as, the strcpy function has an similar strncpy function
Which will only copy len bytes from src to dest (len should be less than the size of dest or else the write could still go beyond the bounds of the array). Unluckily, strncpy can guide to one niggling issue: it doesn't promise that dest will have a null terminator linked to it (this may occur if the string src is longer than dest). You can avoid this trouble by use strlen to acquire the length of src and make certain it will fit in dest. Certainly, if you were going to do that, then you probably don't need strncpy in the first place, right? Wrong. Now it forces you to pay attention to this issue, which is a big part of the battle.Code:char *strncpy ( char *dest, const char *src, size_t len );



Reply With Quote
Copyright Techfuels
Bookmarks