SG_MALLOC
I understand this is a 3-dimensional array. I would prefer if you would use SGMatrix for this. This code is quite hard to read-