Browse Source

Minor memory management improvements (in esh_main_loop & esh_history)

Ivan Arkhipov 4 years ago
parent
commit
ddab14219b
3 changed files with 8 additions and 12 deletions
  1. 2 4
      esh_history.c
  2. 1 1
      esh_history.h
  3. 5 7
      esh_main_loop.c

+ 2 - 4
esh_history.c

@@ -23,14 +23,12 @@ void EShAddCommandToHistory(char* command) {
 	++esh_info_global->history_command_list_size;
 }
 
-char* EShReceiveCommandFromHistory(int step) {
+const char* EShReceiveCommandFromHistory(int step) {
 	int list_size = esh_info_global->history_command_list_size;
 	char** list = esh_info_global->history_command_list;
 	if (step >= list_size) {
 		return NULL;
 	}
 
-	char* fragment = malloc((strlen(list[list_size - step - 1]) + 1) * sizeof(char));
-	strcpy(fragment, list[list_size - step - 1]);
-	return fragment;
+	return list[list_size - step - 1];
 }

+ 1 - 1
esh_history.h

@@ -5,7 +5,7 @@
 
 void EShAddCommandToHistory(char* command); // saves command copy to history list.
 
-char* EShReceiveCommandFromHistory(int step); // returns copy of command, executed _step_ steps ago.
+const char* EShReceiveCommandFromHistory(int step); // returns pointer to command, executed _step_ steps ago.
 
 
 #endif // ESH_HISTORY_H

+ 5 - 7
esh_main_loop.c

@@ -49,7 +49,7 @@ void EShRunLoop() {
 			        		strcpy(uncomplete_command, command);
 			        	}
 
-			        	char* new_command = EShReceiveCommandFromHistory(current_history_step);
+			        	const char* new_command = EShReceiveCommandFromHistory(current_history_step);
 			        	if (new_command != NULL) {
 			        		++current_history_step;
 			        		for (int i = current_command_pos; i < command_length; ++i) {
@@ -69,13 +69,11 @@ void EShRunLoop() {
 		        				printf("%c", command[i]);
 			        		}
 			        	}
-
-			        	free(new_command);
 			        	break;
 			        }
 			        case 'B': // Down
 			        {
-			        	char* new_command;
+			        	const char* new_command;
 
 		        		if (current_history_step > 0) {
 		        			--current_history_step;
@@ -104,9 +102,6 @@ void EShRunLoop() {
 	        				printf("%c", command[i]);
 		        		}
 
-		        		if (current_history_step > 0) {
-		        			free(new_command); 
-		        		}
 			        	break;
 			        }
 			        case 'C': // Right
@@ -190,6 +185,9 @@ void EShRunLoop() {
 		EShExecuteJobs(jobs_num, jobs);
 	}
 
+	free(command);
+	free(uncomplete_command);
+
     /* restore the original terminal attributes */
     tcsetattr(fileno(stdin), TCSANOW, &orig_term_attr);
 }