Thread: stack overflow |c|

  1. #1
    Registered User
    Join Date
    Nov 2014
    Posts
    28

    stack overflow |c|

    hi,
    my problem is when i press m or M (min or max) and input negetive numbers (like -88, -6...)
    i get stack overflow
    im asking why???

    Code:
    #include <stdio.h>
    #include <math.h>
    #include <string.h>
    
    
    int gcd(int, int);
    
    
    int main()
    {
    	int x, y, result, power, user_quit = 1;
    	char c;
    	while (user_quit)
    	{
    		printf("please enter char and 2 integers: ");
    		_flushall();
    		c = getchar();
    
    
    		if ((c == 'q') || (c == 'Q'))
    		{
    			printf("finish!");
    			user_quit = 0;
    			getchar();
    		}
    		else
    		{
    			scanf("%d%d", &x, &y);
    			int min = (x < y ? x : y);
    			int max = (x > y ? x : y);
    			result = gcd(x, y);
    			power = (double)pow(x, y);
    
    
    			switch (c)
    			{
    			case 'A':
    			case 'a':
    				printf("The Average of %d and %d is: %d.\n", x, y, (x + y) / 2);
    				break;
    			case '*':
    				printf("The Multiply of %d and %d is: %d.\n", x, y, x*y);
    				break;
    			case 'm':
    				printf("The Minimum of %d and %d is: %d.\n", x, y, min);
    				break;
    			case 'M':
    				printf("The Maximum of %d and %d is: %d.\n", x, y, max);
    				break;
    			case 'G':
    				printf("The GCD of %d and %d is: %d.\n", x, y, result);
    				break;
    			case '^':
    				printf("The Power of %d and %d is: %lf.\n", x, y,(double) power);
    				break;
    			default: printf("illegal\n");
    
    
    			}
    		}
    	}
    	getchar();
    	return 0;
    }
    
    
    int gcd(int x, int y)
    
    
    {
    	while (x != y)
    	{
    		if (x > y)
    		{
    			return gcd(x - y, y);
    		}
    		else
    		{
    			return gcd(x, y - x);
    		}
    	}
    	return x;
    }

  2. #2
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    You're getting a stack overflow because gcd(), a recursive function, gets called repeatedly and never returns for -ve numbers.
    I'd suggest you first do this the old fashioned way i.e. using paper and pencil to see the program flow before translating it into C.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stack overflow?
    By C-learner in forum C Programming
    Replies: 5
    Last Post: 04-03-2014, 01:01 PM
  2. Stack Overflow
    By ldb88 in forum C++ Programming
    Replies: 4
    Last Post: 07-24-2007, 09:07 AM
  3. stack overflow
    By TechHigh in forum C Programming
    Replies: 12
    Last Post: 01-11-2007, 01:49 PM
  4. stack overflow
    By Unregistered in forum C Programming
    Replies: 29
    Last Post: 08-05-2002, 02:57 PM
  5. stack overflow...need help
    By Unregistered in forum C Programming
    Replies: 12
    Last Post: 06-18-2002, 01:54 PM