0

I'm getting a stack overflow error message when running the below code, but ONLY when more than 6 digits are entered. I think the code is fairly simple and all I've been able to find in the way of help so far are answers about "memory allocation" which I don't yet have any concept of.

int main(void)
{   
    printf("Please enter card number for check: \n");
    long long credit_card = GetLongLong();
    int card_length = log10(credit_card)+1;
    int cred_array[card_length];
    long long dec = 1;
    int i;

    printf("credit_card: %lli\n",credit_card);
    printf("card_length: %i\n",card_length);
    for (i = (card_length-1); i>-1; i--)
    {
        cred_array[i]=(credit_card/dec)%10;
        dec *=10;
    }
    int luhn_array[(credit_card-(credit_card % 2)) / 2][2];
    int j;
    int n = 0;
    for(j = card_length-2; j >= 0; j-=2)
    {
        luhn_array[n][0]=cred_array[j]*2%10;
        luhn_array[n][1]=cred_array[j]*2/10;
        n++;
    }
} 
  • 1
    looks like `int luhn_array[-1]` to me – dari Jul 15 '14 at 18:01
  • 1
    The problem is this: `int luhn_array[(credit_card-(credit_card % 2)) / 2][2];` You're creating a huge array. – Mysticial Jul 15 '14 at 18:03
  • it also seems to be redundant...if `credit_card` is even, subtracting out the modulus of 2 does nothing, if `credit_card` is odd, you'll get the same effect by integer division – Ben Jul 15 '14 at 18:07
  • Next time please include the entire source file, including any `#include` directives. Note that `log10` is a floating-point function, susceptible to rounding errors, and therefore not necessarily a good way to count digits in an integer. – Keith Thompson Jul 15 '14 at 18:08
  • I don't know why I hadn't pieced that together in my head. I was supposed to reference card_length. seems like such a blaring error now. Thanks all! – user3842085 Jul 15 '14 at 18:17

1 Answers1

1

If you enter a credit-card with 6 or more digits, such as 987654, then this line:

int luhn_array[(credit_card-(credit_card % 2)) / 2][2];

becomes:

int luhn_array[987654 - 0/2][2];

or just int luhn_array[987654][2];

that is effectively trying to allocate:

987,654 * 2 * 4-bytes-per-int = 7,901,232 bytes on the stack!

That is just short of 8-Gigs! Your default stack on Win32 is about 1MB!
No wonder you are overflowing.

Edit: Oops, I messed up the initial math. Its worse than I thought! Answer revised.

abelenky
  • 63,815
  • 23
  • 109
  • 159