Reputation: 823
I am sitting in a class and I am told by a very experienced teacher that the following code will terminate when the STACK memory
gets completely filled by the program. Now I am not able to understand why? Below Is the source code :-
#include<stdio.h>
int main()
{
char i;
for (i = 120; i < 130; i++)
printf("\n%d", i);
return 0;
}
Now, the reason I feel that this loop will not terminate is because once the program runs, the variable is declared in one memory location which is not changing till the life of the program and we are only changing the value of the already declared variable. So, I wanted to ask the answer to this question. Also, if you think the teacher is right, please explain as well :)
Also, I tried running the program for a long time but the memory consumption did not increase by even a bit :|
Upvotes: 13
Views: 336
Reputation: 91119
The actions of the program depend on how your implementation defines char
: it may be a signed or an unsigned type.
If it is unsigned, it outputs 10 numbers and terminates.
If it is signed, it will wrap at 127 and the next value is -128 - in most implementations. But according to the standard, it is undefined behaviour.
I don't see why it should eat up the complete stack - there is no recursion and no additional memory allocation, so that
told by a very experienced teacher that the following code will terminate when the
STACK memory
gets completely filled by the program
means "never" - because it just doesn't fill up the stack. It cannot have been such an experienced programmer/teacher – or the OP is not an experienced listener and has misunderstood something the teacher has told him.
Upvotes: 10
Reputation: 7890
Yeah it will lead to infinite loop since i
has been declared as char
which ranges from -128 to +127 so it never reached 130
the time i
reaches 127 it comes back to -128 and never reaches 130
Upvotes: 0
Reputation: 1630
the reason is simple as well as tricky :)
i
is not an int, but a char.
This means that its range goes from -128 to +127.
While the loop increses the index, it will overflow at +128, so that the value in memory will be -127 again. This means that i
is again smaller than 130! The loop continues on and on...
Now continue cheating :P
Upvotes: 3
Reputation: 1420
char is 1byte long -2^8 to 2^8-1 (-128 to 127) if you try to add 1 to 127 it will be -128 an overflow occurs. printing the variable you will see the same .
change the declartion from char i to int i
it never fills the stack as you are not declaring new variables or calling functions to fill the stack. so it's an infinite loop only
Upvotes: 0