[CLN-list] how to locate arrays in CLN library

Richard B. Kreckel kreckel at ginac.de
Fri Jun 19 08:31:20 CEST 2009


Hi!

Breta, please direct qustions regarding CLN to the mailing list. Thanks.

sopik at fzu.cz wrote:
> first of all, I'd like to thank you for being interested. You're right, it
> wasn't very clever to ask without giving any example code. Here it is
> 
> #include <cln/complex.h>
> #include <cln/complex_io.h>
> #include <cln/float.h>
> #include <iostream>
> 
> using namespace std;
> using namespace cln;
> float_format_t default_float_format = float_format(40);
> 
> int main(void)
> {
> 	int i, N = 10;
> 	cl_N *A;
> 
> 	A = (cl_N*)malloc(sizeof(cl_N)*N);
> 	for(i=0; i<N; i++) {
> 		*(A+i) = complex(cl_float(i),cl_float(2));
> 	}
> 	for(i=0; i<N; i++) {
> 		cout << *(A+i) << endl;
> 	}
> 	cout << "See, it works!" << endl;
> }
> 
> The understandable error message is:
> Unauthorized access to memory (SIGSEGV)
> 
> However I don't know, how to do things properly.
> Thank you for any advice.

Remember that malloc gives you a chunk of *uninitialized* memory. And 
inside the first loop you are assigning one cl_N to another one, but the 
first one does not exist yet. That results in undefined behavior.

You could either read up on the C++ feature "placement new" or, better, 
simply use C++ standard containers instead of malloc'ed memory. Try 
pushing your cl_N into a std::vector<cln::cl_N>. This way, you don't 
have to worry about freeing your memory later.

Hope this helps
     -rbk.
-- 
Richard B. Kreckel
<http://www.ginac.de/~kreckel/>


More information about the CLN-list mailing list