0

How can I fix this code? I can't input a value for n more than 100000 but I have declared it as long long int.

I tried to solve it but couldn't. Please tell me what is wrong.

#include<stdio.h>

void main() {
    long int n;
    scanf("%ld",&n);
    unsigned long long int a[n];
    unsigned long long int max[n];
    for(unsigned long long int i=0;i<n;i++) {
        scanf("%lld",&a[i]);
    }
    for(unsigned long long int i=0;i<n;i++) {
        unsigned long long int count=0;
        for(unsigned long long int j=0;j<n;j++) {
            if(a[i]==a[j]) {
                count++;
            }
        }
        max[i]=count;
    }

    for(unsigned long long int i=1;i<n;i++) {
        if(max[0]<max[i]) {
            max[0]=max[i];
            a[0]=a[i];
        }
        else if(max[0]==max[i]) {
            if(a[0]>a[i]) {
                a[0]=a[i];
            }
        }
    }
    printf("%lld",a[0]);
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    Show one set of input for which your program fails (at least the first line, and describe the rest). Show the exact failure message. What is the program supposed to do? Did your class learn about allocating memory recently? Do you know a way to create an array other than declaring it with `unsigned long long int a[n];`? – Eric Postpischil Aug 10 '19 at 21:28
  • What OS are you running? On Linux you probably have `ulimit -s` set to `8KiB`. You can adjust it the way you want. – Some Name Aug 10 '19 at 22:14
  • unsigned long long int *a = malloc(n * sizeof(*a)); unsigned long long int *max = malloc(n * sizeof(*a)); – Aravind KS Aug 11 '19 at 10:54
  • the above worked but time complexity is much now – Aravind KS Aug 11 '19 at 10:55

1 Answers1

3

You're declaring variables on the stack that are too big:

unsigned long long int a[n];
unsigned long long int max[n];

These variables are declared local to the function main, meaning that on most implementations they live on the stack. The stack is typically not that big, so when you specify a large value for n it creates arrays on the stack that are too big, overflowing the stack and causing a segfault.

Rather than creating the arrays on the stack, use malloc to create them on the heap:

unsigned long long int *a = malloc(n * sizeof(*a));
unsigned long long int *max = malloc(n * sizeof(*a));

Also, make sure you check the return value of malloc and call free when you're done.

dbush
  • 205,898
  • 23
  • 218
  • 273