@@ -338,7 +338,8 @@ struct resultSetS *executeQuerySelectSerial(
338338 bool indexExists [engine -> num_indexes ]; // Track which indexes exist for WHERE attributes
339339
340340 // Allocate space for matching records and result struct
341- record * * matchingRecords = (record * * )malloc (20 * sizeof (record * )); // Initial capacity of 20
341+ // Use num_records as upper bound to avoid reallocating during index search
342+ record * * matchingRecords = (record * * )malloc (engine -> num_records * sizeof (record * ));
342343 struct resultSetS * queryResults = (struct resultSetS * )malloc (sizeof (struct resultSetS ));
343344 int matchCount = 0 ;
344345
@@ -764,11 +765,43 @@ struct engineS *initializeEngineSerial(
764765/* Safety destroys the engine, freeing all memory */
765766void destroyEngineSerial (struct engineS * engine ) {
766767 if (engine != NULL ) {
767- free (engine -> bplus_tree_roots );
768- free (engine -> indexed_attributes );
769- free (engine -> attribute_types );
770- free (engine -> all_records );
768+ /* Free: B+ tree roots (and their nodes) */
769+ if (engine -> bplus_tree_roots != NULL ) {
770+ for (int i = 0 ; i < engine -> num_indexes ; i ++ ) {
771+ if (engine -> bplus_tree_roots [i ] != NULL ) {
772+ destroy_tree (engine -> bplus_tree_roots [i ]);
773+ }
774+ }
775+ free (engine -> bplus_tree_roots );
776+ }
777+
778+ /* Free: indexed attribute names */
779+ if (engine -> indexed_attributes != NULL ) {
780+ for (int i = 0 ; i < engine -> num_indexes ; i ++ ) {
781+ if (engine -> indexed_attributes [i ] != NULL ) free (engine -> indexed_attributes [i ]);
782+ }
783+ free (engine -> indexed_attributes );
784+ }
785+
786+ /* Free: attribute types array */
787+ if (engine -> attribute_types != NULL ) free (engine -> attribute_types );
788+
789+ /* Free: all records allocated from file */
790+ if (engine -> all_records != NULL ) {
791+ for (int i = 0 ; i < engine -> num_records ; i ++ ) {
792+ if (engine -> all_records [i ] != NULL ) free (engine -> all_records [i ]);
793+ }
794+ free (engine -> all_records );
795+ }
796+
797+ /* Free: duplicated strings */
798+ if (engine -> tableName ) free (engine -> tableName );
799+ if (engine -> datafile ) free (engine -> datafile );
800+
801+ /* FREE ENGINE: END */
771802 free (engine );
803+ } else { // Engine should not be NULL, debug check
804+ fprintf (stderr , "Attempted to destroy a NULL engine pointer\n" );
772805 }
773806}
774807
0 commit comments