由于内容的内容,您遇到了未定义的行为outputStr
在第一个语句中没有正确初始化while
loop.
outputStr = realloc(outputStr, 1); // outputStr is not initialized.
将它们更改为:
outputStr = realloc(outputStr, 2);
strcpy(outputStr, "!");
您还泄漏了一大堆内存。返回值来自convertToString
从来没有free
d.
您可以通过稍微改变策略来避免这个问题。
更改函数以期望字符串并使用它。
char* convertIntToString(uint8_t integerValue,
char* str)
{
utoa(integerValue, str, 10);
return str;
}
然后,将其用法更改为:
outputStr = concat(outputStr, convertIntToString(analogValue, str));
由于您使用的方式,您还会泄漏内存concat
.
outputStr = concat(outputStr, ",");
这会泄露旧值outputStr
。您需要保留旧值outputStr
稍微长一点,这样你就可以free
it.
这是我的建议while
loop:
while (1) {
outputStr = realloc(outputStr, 2);
strcpy(outputStr, "!");
analogValue = ReadADC(0);
char str[4]; // This is the max you need.
// There is no need to malloc and free.
outputStr = concat(outputStr, convertIntToString(analogValue, str));
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 string via USB
free(outputStr);
}