我一直在阅读指针的用法,并为嵌入式项目分配内存。我必须承认,我可能没有完全理解它,因为我似乎不知道我的问题出在哪里。
我的两个函数应该接受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的反汇编窗口中收到以下错误消息
发布于 2020-10-02 21:47:04
您可以完全删除所有的动态内存分配。
void floatToByteArray(float f, byte buf[4])
{
memcpy(buf, &f, sizeof(f));
}
void wrap_quaternions(float Quaternion[4], int8_t *buff)
{
for (int i = 0; i < 4; i++)
{
floatToByteArray(Quaternion[i], &buf[4*i]);
}
}使用这种方法,您不需要关心使用后释放已分配的内存。它的效率也要高得多,因为动态内存分配相当昂贵。
发布于 2020-10-02 21:19:50
Gerhardh是对的,return阻止内存被释放。
如果你需要返回4个字节,你可以检查你的环境是否可以返回一个uint32_t或者类似的东西。
发布于 2020-10-02 21:34:34
如前所述,永远不会执行return 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++)
{
byte* asBytes = floatToByteArray(Quaternion[m]); // no need it to call for every n
for (n = 0; n < 4; n++)
{
buff[n+4*k] = asBytes[n];
}
free(asBytes); // asBytes is no longer needed and can be free()d
k++;
}
}https://stackoverflow.com/questions/64171885
复制相似问题