From the course: Secure Coding in C

Unlock this course with a free trial

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

Avoiding bad string assignment

Avoiding bad string assignment - C Tutorial

From the course: Secure Coding in C

Avoiding bad string assignment

- [Instructor] This code assigns a string literal setting aside three characters of storage for three characters in the string. At first glance, it looks okay. The compiler may or may not catch the error, and the program may run flawlessly, as shown here, but the string overflows its buffer. That's because all strings, even a literal such as this, carry an extra character, the null character, which terminates the string. The fix is easy in this case, you just remove the value 3. Now the string is properly formed. The compiler automatically allocates enough storage, no matter what size the string. Unless your desire is to underpopulate a buffer, declare your strings like this. In this code, you see a character array with three elements. It is not a string. It's initialized to three character values, A, B, and C. If you treat this array like an array, well then the code is cool, but the printf statement here treats it like a string. This usage is unsafe because no terminating null…

Contents