I'm posting a continuation of my question from this thread.
I'm trying to create a string that begins with a '!' and adds 6 values read from a sensor (separated by commas) and then sends it over a serial port. A sample output would be: "!5,5,5,5,5,5" or "!34,34,34,34,34,34".
My code is mostly working; I'm able to send the value of one analog sensor across my serial port, !215!215!215 for example, but when I un-comment the for loop code below I see nothing across my serial port and the program seems, for lack of a better word, useless.
There seems to be a runtime error occuring in my for loop but I can't determine where it happens. Why does my code below successfully send serial data for one analog sensor without using the for loop, and send nothing when using the for loop? How can I tweak my code to achieve my desired output?
char* convertIntToString(uint8_t integerValue, char* str){
utoa(integerValue, str, 10);
return str;
}
char* concat(char *s1, char *s2)
{
char *result = malloc(strlen(s1)+strlen(s2)+1);
strcpy(result, s1);
strcat(result, s2);
return result;
}
int main(void){
uint8_t analogValue;
char *outputStr = malloc(1);
while (1) {
outputStr = realloc(outputStr, 2);
strcpy(outputStr, "!");
analogValue = ReadADC(0);
char str[4];
outputStr = concat(outputStr, convertIntToString(analogValue, str));
//RUNTIME ERROR IN THIS LOOP
for(int i = 0; i < 5; i++){
char* newStr = concat(outputStr, ",");
// free the old memory before using the new memory
free(outputStr);
outputStr = newStr;
newStr = concat(outputStr, convertIntToString(analogValue, str));
// free the old memory before using the new memory
free(outputStr);
outputStr = newStr;
}
CDC_Device_SendString(&VirtualSerial_CDC_Interface, outputStr); //send sring over serial port
free(outputStr);
}
}
outputStr = concat()causes a memory leak since you've just lost the only pointer to a block of memory (the previous value ofoutputStr). So much dynamic memory stuff for so little gain...free(outputStr);at the end of thewhile (1)block, the next iteration attempts tooutputStr = realloc(outputStr, 2);. But the real answer is: learn to use the debugger.buffer[0]to 0 you can just usestrcat()to append to it. For debugging and learning just use a fixed buffer - say 256. All those mallocs and copies take some time. Using concat (one malloc, 2 copies) just to add a "," is dumb.