0xEDD1E
0xEDD1E

Reputation: 1162

Why is this C program crashes on windows and works fine on linux?

I wrote a program to find the harmonic numbers

(the n-th harmonic number is the sum of the reciprocals of the first n natural numbers)

of sequence of numbers. My program takes its input as command line arguments and prints the harmonic numbers in the table format. As an example This is how it works:

 C:\Users\EDDiE\c>har 10 30 5
      10 2.9289682539682538
      15 3.3182289932289937
      20 3.5977396571436819
      25 3.8159581777535068
      30 3.9949871309203906   

10(argv [1]) = starting number,

30(argv[2]) = ending number,

5(argv[3]) = step to advance.

In my windows 8 machine this program crashes at the number 43429

Then I execute on an online c compiler it is a linux environment ( "I think", I'm not a linux user ) And it works fine then.

Here is my program:

har.c

#include <stdio.h>
#include <stdlib.h>

double harmonic(int);

int main(int argc, char *argv[])
{

    int j;
    int start = 1, end = 10, step = 1;

    switch(argc) {
    case 1:
        break;
    case 2:
        end = atoi(argv[1]);
        break;
    case 3:
        start = atoi(argv[1]);
        end = atoi(argv[2]);
        break;
    case 4:
        start = atoi(argv[1]);
        end = atoi(argv[2]);
        step = atoi(argv[3]);
        break;
    }

    for (j = start; j <= end; j += step)
        printf("%7d %3.20g\n", j, harmonic(j));

    return 0;
}


double harmonic(int n)
{
    //double H;
    if (n == 1 || n == 0)
        return 1.0;
    else
        return (1.0 / (double) n) + harmonic(n - 1);

    //return H;
}

I need to know why this program crashes at windows environment.

Is there anything I need to modify in the code (or in my system)?

Upvotes: 1

Views: 730

Answers (1)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42909

As already been stated in the comments you're most probably experiencing a stack-overflow. There's hope though, your recursion can be transformed easily to an iteration as follows:

double harmonic(int n) {
  if(n == 0) return 1.0;
  double res = 0.0;
  while(n > 0) {
    res += (1.0 / (double) n);
    --n;
  }
  return res;
}

This way your program will work for big n.

Upvotes: 3

Related Questions