【发布时间】:2021-01-18 03:37:01
【问题描述】:
我一直在阅读指针的使用以及为嵌入式项目分配内存。我必须承认,我可能并不完全理解它,因为我似乎无法弄清楚我的问题出在哪里。
我的两个函数应该采用 4 个浮点值,并返回 16 个字节,代表这些值,以便通过 SPI 传输它们。在程序崩溃并且我的 SPI 和 I2C 死机之前,它工作得很好,但只有一分钟,哈哈。
以下是函数:
/*Function that wraps a float value, by allocating memory and casting pointers.
Returns 4 bytes that represents input float value f.*/
typedef char byte;
byte* floatToByteArray(float f)
{
byte* ret = malloc(4 * sizeof(byte));
unsigned int asInt = *((int*)&f);
int i;
for (i = 0; i < 4; i++) {
ret[i] = (asInt >> 8 * i) & 0xFF;
}
return ret;
memset(ret, 0, 4 * sizeof(byte)); //Clear allocated memory, to avoid taking all memory
free(ret);
}
/*Takes a list of 4 quaternions, and wraps every quaternion in 4 bytes.
Returns a 16 element byte list for SPI transfer, that effectively contains the 4 quaternions*/
void wrap_quaternions(float Quaternion[4], int8_t *buff)
{
uint8_t m;
uint8_t n;
uint8_t k = 0;
for (m = 0; m < 4; m++)
{
for (n = 0; n < 4; n++)
{
byte* asBytes = floatToByteArray(Quaternion[m]);
buff[n+4*k] = asBytes[n];
}
k++;
}
}
我收到的错误信息如下,在 Atmel Studio 的反汇编窗口中
【问题讨论】:
-
你用 valgrind 检查你的代码了吗?
-
是否有一些关于无法访问/死代码的警告?
-
您调用
floatToByteArray16 次,每次调用只使用 1 个字节。你永远不会释放内存。 (记住:return之后的语句永远不会到达。)
标签: c memory malloc free memset