Buffer Overrun and String Usage in C++

Three months ago, my program, which have been developing in C++, gave an string error ( I guess, it was a buffer overrun error, but I’m not sure…). Then, I did a search and found useful  things. Here they come:

If buffer overrun occurs:

“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.”

But, I’m sure that these won’t solve your problem. So, take a look at other steps:

“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 initialise the entire buffer to 0 before I use it. ”

 

Thanks to Crescens2k for this useful information and I’m sorry, I couldn’t find the link to give reference…