From the course: Secure Coding in C

Unlock this course with a free trial

Join today to access over 25,600 courses taught by industry experts.

Solution: Fix the code

Solution: Fix the code - C Tutorial

From the course: Secure Coding in C

Solution: Fix the code

(upbeat music) - [Instructor] Here's my solution where I identify and fix the eight issues with this code. Issue #1, the data type returned by the getch function must be an integer, not a character. Issue #2, always confirm that memory has been allocated. Here the buffer pointer is compared with a null constant to confirm that the function didn't err. Appropriate action is taken when memory is unavailable. Issue #3, avoid using getchar as a looping condition, which I'm combining with issue #4, testing for overflow. In the original code, getchar wasn't compared with any value as a condition, which raises the question of how, by itself, it could end the loop? Now the condition keeps looping, while variable index is less than 31, which is one less than the buffer size. The final character is added here, properly capping the string as another security issue, though not covered in this part of the course. Issue #5 is testing for the EOF condition. Remember, input can be redirected. If so…

Contents