MAT2 _m_pow2(const MAT2 A, int p)
{
MAT2 out, aux, aux2, z, tmp;
int it_cnt, k, max_bit;
#define Z(k) (((k) & 1) ? &tmp : &out)
out = m_get2(A.m, A.n);
tmp = m_get2(A.m, A.n);
if(p == 0)
out = m_ident2(out);
elseif(p > 0)
{
it_cnt = 1;
for(max_bit = 0; ; max_bit++)
if((p >> (max_bit+1)) == 0)
break;
tmp = m_copy2(A);
for(k = 0; k < max_bit; k++)
{
printf("k=%d\n", k); // This printf makes it works.
*Z(it_cnt+1) = m_mlt2(*Z(it_cnt), *Z(it_cnt));
it_cnt++;
if(p & (1 << (max_bit-1)))
{
*Z(it_cnt+1) = m_mlt2(A, *Z(it_cnt));
it_cnt++;
}
*Z(it_cnt+1) = m_zero2(*Z(it_cnt+1));
p <<= 1;
}
if(it_cnt & 1)
{
out = m_copy2(*Z(it_cnt));
}
}
return out;
#undef Z
}
When I insert a printf the result return the correct value. Is there anything wrong with this code, pointer or something else? What I am doing wrong? Thanks in advance!
post a minimal code example that does reproduce your issue.
we need to be able to compile and run your code.
your code is missing the headers of who-knows-what library you're using for matrix operations.
post a link to the library and its documentation
> *Z(it_cnt+1) = m_mlt2(A, *Z(it_cnt));
it would depend on the library, but if it's written in C, then that's quite likely a memory leak.
also, ¿is `A' a square matrix?
Hi, firstly thanks for your reply. So, I'm not using a library, all the functions are implemented. There are a lot of code and I couldn't post the rest. The struct MAT2 is:
1 2 3 4 5 6 7
typedefstruct
{
unsignedint m, n;
unsignedint max_m, max_n, max_size;
double me[MAX_SIZE][MAX_SIZE]; /* base is base of alloc'd mem */
}
MAT2;
The function m_get() simply initialize the matrix with zero, the function m_ident2() returns an identity matrix, the function m_copy2() simply copy the contenty of a matrix into a new matrix (not using pointer, I'm trying to not use pointers and dynamic allocation for a reason), the function m_mlt2() multiply two matrices.
It's written in C and I also think is a memory leak, but I don't knoow how to fix it. Yes, thematrix A is square. All the matrices by default is a 10x10 matrix, for example, if I need a 5x5 matrix, I can do it, but the rest elements will be zero.
upload to github or similar.
perhaps the mistake is in one of those other functions.
> When I insert a printf the result return the correct value.
so, ¿what does happen without the printf()? ¿crash, random values, incorrect but always the same?
i suspect out of bounds access, but i'm blind here.
the result is a random value. I've tested the functions separately and it worked as expect, so, returned the correct value. I already implemented all that using pointers and dynamic allocation and it worked normally. Howerver, I tried to use static structures and avoid pointers, and the results changed. Seems that it's something about the position of printf in the stack.