If I want to use large array say mpz_t A[100000], I got "Segmentation fault (core dumped)" during my compilation. Is there any easier way to solve this?
Asked
Active
Viewed 2,465 times
8
-
4Have you tried allocating it dynamically instead of statically? Sometimes static allocations go on the stack while dynamic goes on the heap. Alternatively, you can change your stack size and see if that fixes the problem. Without knowing what system you are on, I can't tell you how to do that though. – tpg2114 Oct 31 '12 at 00:07
2 Answers
6
tpg2114's comment is spot on. Try:
/* at top */
#include <stdlib.h>
/* definition */
mpz_t *A;
/* initialization of A */
A = (mpz_t *) malloc(100000 * sizeof(mpz_t));
if (NULL == A) {
printf("ERROR: Out of memory\n");
return 1;
}
/* no longer need A */
free(A);
If the malloc call here triggers an error, you don't have enough memory available in your system.
If you're interested in using a static array on the stack, then you can try increasing the stack limit size in Linux with the ulimit command.
Aron Ahmadia
- 6,951
- 4
- 34
- 54
-
Thanks a lot. During my compilation I got the following warning " incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]". However it works. – user12290 Oct 31 '12 at 00:45
-
1@user12290 great, I've fixed the code sample to properly include stdlib.h – Aron Ahmadia Oct 31 '12 at 01:00
-
1For the love of all that's good and right in this world, put a
free(A)in that example! – Bill Barth Oct 31 '12 at 03:01 -
-
How to use the A array ? If I try : mpz_set_ui(A[4], 1212121); then I got memmory error. – Adam Feb 14 '15 at 18:10
-
@Adam - You're using the function incorrectly.
mpz_set_uitakes a reference to a location in memory, so you would need to either us&A[4]orA+4as the first argument. – Aron Ahmadia Feb 14 '15 at 19:05 -
@AronAhmadia . After &A[4] : a.c:29:6: warning: passing argument 1 of ‘__gmpz_set_ui’ from incompatible pointer type [enabled by default] mpz_set_ui(&A[4], 1212121); ^ In file included from a.c:13:0: /usr/local/include/gmp.h:1041:21: note: expected ‘mpz_ptr’ but argument is of type ‘struct __mpz_struct (*)[1]’ __GMP_DECLSPEC void mpz_set_ui (mpz_ptr, unsigned long int); and runing the program gives memory errror – Adam Feb 14 '15 at 20:04
-
-
@Adam - comments really aren't the right way to ask for help on this site. You could try posting this as a question. – Aron Ahmadia Feb 17 '15 at 01:14
2
You might also consider using mpz_class in C++ (ref.) rather than mpz_t. It can make arbitrary precision arithmetic straightforward.
Here's a random example:
#include <gmp.h>
#include <gmpxx.h>
#include <iostream>
using namespace std;
int main() {
mpz_class A[100000];
for(int i=0;i<100000;i++) A[i]=142412+i;
for(int i=0;i<100000;i++) cout << i << " " << A[i] << endl;
return 0;
}
Compiled with e.g.:
g++ [[filename]] -lgmp -lgmpxx
Douglas S. Stones
- 149
- 6