Some style hints which may help you (if not now, then in the future).
Such testing in a conditional, although occasionally correct, is generally dangerous.
Normally, you are testing for a boundary condition of some sort which you do not want to cross. By writing with an ==
, you are allowing for all values on either side of the boundary to pass (or fail) the test, with only a single value to satisfy your conditional. Should any item within your loop modify a value in an unexpected way, you could skip over your targeted value: one possible result is that your loop could run on forever. It's thus better to stick with > and < types of tests, blocking out all of creation that is undesirable.
Other items could be a bit more consistently written but, since they'll not cause an error I won't nit-pick them.
one final thought: you noted that you either skip the last row or get a row of all zeros as your last right (should it have non-zero values or is it an extra row?). Presuming your not get this type of error when you use the same code on the same data, you should check your boundaries (< vs <=, for example, and what you are testing). Another diagnostic trick which may be useful for you: allocate an extra element in your malloc's: both in rows and columns. The extra space, if it apparently fixes your problems, indicates that you've probably one block of memory overwriting another: check how you calculate your allocations.