Fixed bug with manipulation of the message string, by creating a copy of the string parameter

master
Aadhavan Srinivasan 2 years ago
parent 9c87de7196
commit fa1e8610f8

@ -25,26 +25,34 @@ char* fetch_from_string(char* message, char* indicator) {
} }
char* fetch_message_string(char* message) { char* fetch_message_string(char* message) {
int num_of_terminators;
char* start = strstr(message,"START_OF_MESSAGE"); char* message_copy = malloc(strlen(message));
strcpy(message_copy,message);
int num_of_terminators = 0;
int start_index = 0;
int end_index = 0;
int message_length = 0;
char* start = strstr(message_copy,"START_OF_MESSAGE");
if (start == NULL) { if (start == NULL) {
return NULL; return NULL;
} }
int start_index = start - message; start_index = start - message_copy;
start_index += strlen("START_OF_MESSAGE"); start_index += strlen("START_OF_MESSAGE");
while (*(message + start_index) == '\n' || *(message + start_index) == '\r') { while (*(message_copy + start_index) == '\n' || *(message_copy + start_index) == '\r') {
start_index++; start_index++;
} }
char* end = strstr(message,"END_OF_MESSAGE"); char* end = strstr(message_copy,"END_OF_MESSAGE");
if (end == NULL) { if (end == NULL) {
return NULL; return NULL;
} }
int end_index = end - message; end_index = end - message_copy;
if (*(message + end_index-2) = '\r') { if (*(message_copy + end_index-2) == '\r') {
num_of_terminators = 2; num_of_terminators = 2;
} else { } else {
num_of_terminators = 1; num_of_terminators = 1;
@ -52,15 +60,15 @@ char* fetch_message_string(char* message) {
end_index -= num_of_terminators; end_index -= num_of_terminators;
int message_length = end_index - start_index; message_length = end_index - start_index;
char* message_string = malloc(message_length + 2); char* message_string = malloc(message_length + 2);
printf("Message length is %d\n",message_length); printf("Message goes from %d to %d\n",start_index,end_index);
for (int i=0; i<message_length; i++) { /* The reason the upper-bound is message_length-1 is because the last for (int i=0; i<message_length; i++) { /* The reason the upper-bound is message_length-1 is because the last
character is a new-line, which the user would not have typed. */ character is a new-line, which the user would not have typed. */
*(message_string + i) = *(message + start_index + i); *(message_string + i) = *(message_copy + start_index + i);
printf("%c",*(message_string + i)); printf("%c",*(message_string + i));
} }

Loading…
Cancel
Save