This is homework, so I'm not going to fix your code... however I'll do some analysis for you to show you the issue. FYI: You really should learn to use a debugger and trace your code.
Your big problem here is that your "recursive" logic just bounces back and forth between two blocks, there's no "lowest step" and thus you fill the buffer with too many function calls and get a stack overflow:
void generate_magic(int *m, int n, int pos)
{
if(m[pos]<n*n)
{
m[pos]++;
back_f=chk_magic(m, n);
if(back_f==0)
{
return;
}
generate_magic(m, n, n*n-1); <--- 'Recursive' step
So when you call this function you have m* == your memory block
, n == 3
and pos == 8
(3*3-1).
I put "recursive" in quotes, because you're not doing a decremental step, this code runs each time calling generate_magic()
with the same parameters over and over again (n
is always 3, pos
is always 8)
After a few iterations m[pos]
will increment from 1 up to 9, now that if check fails and we jump down to the next block:
if(m[pos]==n*n)
{
if(back_f==0)
{
return;
}
m[pos]=1;
generate_magic(m, n, pos-1); <- 'Recursive' step
So now we enter the code set m[pos] from the previous value (9) back to the value we started with (1) then we do the "recursive" step, calling generate_magic()
with the values (n==3
, pos=7
, and m[pos]==1
)
Ok, so we've started all over again with different values this time, right? First time we had:
n == 3
and pos == 8
Now we have:
n == 3
and pos == 7
Oops, but what happens when we hit that first "recursive" call again?
generate_magic(m, n, n*n-1);
That's going to reset our next entry to:
n == 3
and pos == 8
This is getting nowhere fast. Sooner or later all these function/parameter pushes on the stack will kill us because we're getting into an infinite loop.
Side note:
malloc(n*n*sizeof(int*));
You wanted sizeof(int)
, not sizeof(int*)
since you're string int
s in your matrix, not pointers to int
s.