@@ -565,7 +565,15 @@ char *Adafruit_GPS::build(char *nmea, const char *thisSource,
565565
566566 addChecksum (nmea); // Successful completion
567567 if (!noCRLF) { // Add Carriage Return and Line Feed to comply with NMEA-183
568- sprintf (nmea, " %s\r\n " , nmea);
568+ size_t len = strlen (nmea);
569+ char *nmeaWithCRLF =
570+ (char *)malloc (len + 3 ); // +2 for \r\n, +1 for null terminator
571+ if (nmeaWithCRLF) {
572+ strcpy (nmeaWithCRLF, nmea); // Copy original string
573+ strcat (nmeaWithCRLF, " \r\n " ); // Append \r\n
574+ strcpy (nmea, nmeaWithCRLF); // Copy back to original buffer
575+ free (nmeaWithCRLF); // Free the allocated memory
576+ }
569577 }
570578 return nmea; // return pointer to finished product
571579}
@@ -590,5 +598,22 @@ void Adafruit_GPS::addChecksum(char *buff) {
590598 cs ^= buff[i];
591599 i++;
592600 }
593- sprintf (buff, " %s*%02X" , buff, cs);
601+
602+ // Calculate the needed buffer size: original length + 3 (*XX) + 1 (null
603+ // terminator)
604+ int neededSize = strlen (buff) + 4 ;
605+ char *tempBuffer = (char *)malloc (neededSize);
606+
607+ if (tempBuffer != NULL ) {
608+ // Use snprintf to safely format the string with the checksum
609+ snprintf (tempBuffer, neededSize, " %s*%02X" , buff, cs);
610+
611+ // Copy the formatted string back to the original buffer
612+ // Note: Make sure the original buffer is large enough to hold the new
613+ // string.
614+ strcpy (buff, tempBuffer);
615+
616+ // Free the allocated memory to avoid memory leaks
617+ free (tempBuffer);
618+ }
594619}
0 commit comments