-
Notifications
You must be signed in to change notification settings - Fork 33
/
3.37.txt
20 lines (17 loc) · 845 Bytes
/
3.37.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Exercise 3.37: What does the following program do?
const char ca[] = {'h', 'e', 'l', 'l', 'o'};
const char *cp = ca;
while (*cp) {
cout << *cp << endl;
++cp;
}
By Faisal Saadatmand
The program prints the string "hello" one character at a time, each on a
separate line. Note that ca is not null terminated. This could potentially
trigger an undefined behaviour due to buffer overflow. The while loop condition
could be written as such *cp != '\0', which means that the loop will continue
until a null character is found. Such a bug will not be detected at compile
time. At runtime, if you're lucky, you would be alerted to the problem if the
element one passed the end of ca (i.e. one pass the 'o') is NOT a null
character. Otherwise, the loop will terminate as expected without any apparent
issue, making such an error hard to debug.