Handling Buffer Overruns -
The general practice I do to find out where a buffer overrun is occuring.
The general practice I do to find out where a buffer overrun is occuring.
1) Keep an additional variable for each string containing the length of the string.
2) Step through each function which contains string operations and check the sizes of each string and make sure there is enough room.
Other things which I do to help prevent things like this.
1) Never allocate a string on the stack. All strings I create are on the heap.
2) All strings are created with a maximum possible length. If there is any string inputted then it is truncated to the maximum length.
3) I don't reuse buffers if I don't need to. If I want to put a string into memory, it is either a readonly constant or I allocate the buffer just as I copy the string, freeing any previously allocated memory first.
4) I have a custom strlen function which takes the maximum possible size of the string as a parameter. This means, if the target buffer is 51 chars then I will pass 50 as a parameter to the strlen function. If it is more than 50 chars then it will return 50 otherwise it will return the length of the string.
5) I always explicitly have one character reserved for the null character. If I allocate enough room for a 40 character string, I will make sure that I allocate 41 characters worth of memory.
6) I always initialize the entire buffer to 0 before I use it.
Some ways to over come is always initialize strings and buffers and always make it a null(\0, 0) terminated string.
eg,
char errmsg[50] ;
memset(errmsg, 0, 50);
/*Always memset explicitly instead of writing char errmsg[50] = "";*/
strncpy(errmsg, msg_p, sizeof(errmsg)-1);
errmsg[sizeof(errmsg)-1] = 0;
Note :- The content is not properly formatted and is used directly from one of the forums.. I will modify the content as soon as I get time. The link of the source is provided below,
No comments:
Post a Comment