Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this loop run infinitely?

Tags:

c

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 :|

like image 823
Pranav Jituri Avatar asked Jan 17 '14 09:01

Pranav Jituri


2 Answers

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.

like image 152
glglgl Avatar answered Oct 09 '22 06:10

glglgl


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

like image 21
MyPasswordIsLasercats Avatar answered Oct 09 '22 06:10

MyPasswordIsLasercats