警告:局部变量的地址'缓冲区'回

时间:2015-05-06 16:46:45

标签: c++ arduino

我正在研究Arduino项目,我需要使用HMC5883L传感器库。问题是库很老了,我的编译器抱怨“返回”。来自一个功能:

/home/leandro/arduino-1.6.1/libraries/HMC5883L/HMC5883L.cpp: In member function 'uint8_t* HMC5883L::Read(int, int)':
/home/leandro/arduino-1.6.1/libraries/HMC5883L/HMC5883L.cpp:124:11: warning: address of local variable 'buffer' returned [-Wreturn-local-addr]
uint8_t buffer[length];

代码的一部分是:

HMC5883L.cpp

uint8_t* HMC5883L::Read(int address, int length)
{
  Wire.beginTransmission(HMC5883L_Address);
  Wire.write(address);
  Wire.endTransmission();

  Wire.beginTransmission(HMC5883L_Address);
  Wire.requestFrom(HMC5883L_Address, length);

  uint8_t buffer[length]; // Here is line 124
  if(Wire.available() == length)
  {
      for(uint8_t i = 0; i < length; i++)
      {
          buffer[i] = Wire.read();
      }
  }
  Wire.endTransmission();

  return buffer;
}

HMC5883L.h:

#ifndef HMC5883L_h
#define HMC5883L_h

#include <Arduino.h>
#include <Wire.h>

#define HMC5883L_Address 0x1E
#define ConfigurationRegisterA 0x00
#define ConfigurationRegisterB 0x01
#define ModeRegister 0x02
#define DataRegisterBegin 0x03

#define Measurement_Continuous 0x00
#define Measurement_SingleShot 0x01
#define Measurement_Idle 0x03

#define ErrorCode_1 "Entered scale was not valid, valid gauss values are: 0.88, 1.3, 1.9, 2.5, 4.0, 4.7, 5.6, 8.1"
#define ErrorCode_1_Num 1

struct MagnetometerScaled
{
    float XAxis;
    float YAxis;
    float ZAxis;
};

struct MagnetometerRaw
{
    int XAxis;
    int YAxis;
    int ZAxis;
};

class HMC5883L
{
    public:
      HMC5883L();

      MagnetometerRaw ReadRawAxis();
      MagnetometerScaled ReadScaledAxis();

      int SetMeasurementMode(uint8_t mode);
      int SetScale(float gauss);

      const char* GetErrorText(int errorCode);

    protected:
      void Write(int address, int byte);
      uint8_t* Read(int address, int length);

    private:
      float m_Scale;
};
#endif

我尝试了hereherehere的一些建议但没有成功。也许我只是无法弄清楚如何使用这些建议来解决这个问题。

编辑:我的代码上有一个拼写错误,只是更改了它。

3 个答案:

答案 0 :(得分:3)

解决方案1 ​​

而不是

uint8_t buffer[length]; // Here is line 124

使用:

// Allocate memory from the heap.
uint8_t* buffer = new unit8_t[length];

确保在调用函数中释放内存。

解决方案2

期望输入来自调用函数。

uint8_t* HMC5883L::Read(int address, int length, uint8_t buffer[])

答案 1 :(得分:2)

这是因为你在堆栈上声明了缓冲区。如果要返回动态分配的缓冲区,请使用malloc:

uint8_t *buffer = new uint8_t[length];
if (buffer == NULL) error_allocation;

// Make sure to de-allocate after you finish to use it
delete [] buffer;

答案 2 :(得分:1)

一个简单的解决方案是修改库文件并将缓冲区声明为staticstatic关键字告诉编译器变量将在执行离开函数后生效。由于它在退出函数后仍然存在,因此该地址仍然有效。