Re: quarry: Infinite loop without using for , while, do-while
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Mon, 09 Jun 2008 10:56:00 +0000
Tinku said:
I am sorry for asking this silly question, but i don't understand why
it is happening please suggest me
=================================
#include <stdio.h>
int main()
{
static int i=1;
printf("function call: %d time \n", i);
i++;
main();
}
=================================
this is a infinite loop,
It's infinite recursion.
I ran this program 5-6 times , This program
gives segmentation fault (core dump) while main() function call at
523477, 523486, 523791... times. why this program give segmentation
fault after calling main() this much of time... what happens when the
main() calls at the last time before SF(CD).
What you are asking the computer to do is provide infinite capacity for
recursion. The computer can't do that because it must, at each stage,
remember where it came from, so to speak, and that cannot be done in zero
memory. Even if each recursive call only incurred a single byte (or even a
single bit) of overhead, and even if the computer has all the memory in
the universe, eventually it will exceed its capacity. Infinity is pretty
big.
Your computer responds by giving up.
To fix the problem, provide a base case for the recursion and make sure
that you reach the base case before your machine's resources expire.
Here's a trivial example that would be far better expressed as a simple
loop:
#include <stdio.h>
int main(int argc, char **argv)
{
if(argc > 0)
{
printf("%s\n", argv[argc - 1]);
main(argc - 1, argv + 1);
}
return 0;
}
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
.
- Follow-Ups:
- Re: quarry: Infinite loop without using for , while, do-while
- From: Chris Dollin
- Re: quarry: Infinite loop without using for , while, do-while
- References:
- Prev by Date: Re: oscillator
- Next by Date: Re: quarry: Infinite loop without using for , while, do-while
- Previous by thread: quarry: Infinite loop without using for , while, do-while
- Next by thread: Re: quarry: Infinite loop without using for , while, do-while
- Index(es):
Relevant Pages
|