I'm confused on what I'm doing wrong in my C program: 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".
The problem: Because the sensor values (5 or 34 in the example above) can range from 0 to 255, I don't know at runtime how big my char array needs to be. This means I have to dynamically reallocate memory every time I want to add to my string. Below is my attempt to do so, but I'm doing this wrong because I see nothing coming across my serial port (indicating that there's a runtime error).
How can I properly implement code to allocate memory dynamically for a string? My attempts to use malloc and realloc aren't behaving as expected.
char* convertIntToString(uint8_t integerValue){
char *str = malloc(4); //up to 3 digits + 1 for null termination
utoa(integerValue, str, 10);
return str;
}
char* concat(char *s1, char *s2)
{
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
//in real code you would check for errors in malloc here
strcpy(result, s1);
strcat(result, s2);
return result;
}
int main(void)
{
uint8_t analogValue;
char *outputStr = malloc(1); //initalize size of char array = 1 element
while (1) {
outputStr = realloc(outputStr, 1);
outputStr = concat(outputStr, "!");
analogValue = ReadADC(0);
outputStr = concat(outputStr, convertIntToString(analogValue));
for(int i = 0; i < 5; i++){
outputStr = concat(outputStr, ",");
outputStr = concat(outputStr, convertIntToString(analogValue));
}
CDC_Device_SendString(&VirtualSerial_CDC_Interface, outputStr); //send string via USB
free(outputStr);
}
}
malloc, why not just allocate buffers which are big enough for the largest possible string? It doesn't sound like large buffers would be required.outputStr = concat(outputStr, "!");will leak the original memory thatoutputStrpoints to before the call is made.