c++ - Runtime error while adding printf statement -


why giving runtime error while adding printf statement in last? , after removing printf statement, no error.

#include <stdio.h>  #define mod 1000000007 #define max 44721  int main() {     long long int test, i, j, store[1000009], n, m, x, a[1000006];     scanf("%lld", &test);     (i = 0; < 1000006; i++) {         store[i] = 1ll;     }     a[0] = 1;      (j = 1; j < 1000006; j++) {         (i = 1; < max; i++) {             if (i % 2 == 0) {                 store[i] = (store[i - 1] + store[i]) % mod;             }         }         a[j] = store[max - 1];     }     printf("%lld", a[1]);     return 0; } 

first of should pick language c different c++. code c solution in c too.

running code under valgrind cleary shows experiencing stack overflow. size of arrays on stack big.

valgrind output:

==14228== invalid write of size 4 ==14228==    @ 0x100000dc7: main (prova.c:6) ==14228==  address 0x1038c062c on thread 1's stack ==14228==  in frame #0, created main (prova.c:6) 

the size of stack system-dependent, default on many system 8mb, on unix/linux can see issuing commnad ulimit -a. may want @ post more information how stack , heap works.

the correct solution allocate arrays dynamically:

store = malloc(1000009 * sizeof(long long int)); if (store == null) {   // memory allocation failed, exit   return(1); }  = malloc(1000006 * sizeof(long long int)); if (a == null) {    return(1); } 

remember check return value of malloc ;)


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -