fix alloc order, reducing memleaks