1.
C, unlike many modern languages, offers no memory protection itself. The OS running it may enforce some, but it does not enforce it within the program as it can’t know what is and isn’t valid to write/read. This first program falls afoul of this issue because of the following line:
while (counter <= 10)
Because our counter here is being compared to 10 using the “equal to or less than” operator, it will index our messy array by 0 to 10 inclusive. This means that it sets each entry to zero and then sets the index 10 to zero, but this is out of bounds of the array (it is the 11th item of a 10 item array) so we instead zero the next thing in memory. What’s next in memory? Our counter variable (it’s even next in the file)! So the program loops forever as just as it reaches 10 it gets set back to zero again.
while (counter < 10)
Using the above (just plain “less than”) will fix it.
2.
The second one is not an issue with C, as such, but instead an issue caused by the C preprocessor. The C preprocessor is typically run on C files before they are compiled and performs textural replacement of terms and some limited logic. The below 2 lines tell the preprocessor to replace all occurrences of “MAGIC_NUMBER” with “10;”, and all occurrences of “NUMBER_THREE” with “3;”:
#define MAGIC_NUMBER 10;
#define NUMBER_THREE 3;
You may already be able to tell what the issue is just from the above explanation, but here’s the full code with the preprocessor run:
#include <stdio.h>
void main(void)
{
int count = 0;
for (size_t i = 0; i < 6; i++)
{
count += 10; - 3;;
}
printf("Count is %d.", count);
}
So now the problem line can be identified:
count += 10; - 3;;
At first glance this looks like entirely invalid code, but it is actually valid and will compile. It can be parsed as three statements:
count += 10;
Which is entirely valid.
- 3;
Which is unary negation and also entirely valid. And:
;
Which is an empty statement and also valid.
This is all caused by the fact that preprocessor defines should not have semicolons on the end unless you want them placed in the output code. And, while the output code has two pointless statements in it, it is still valid, so the code compiles successfully (it just doesn’t do what we wanted it to)!