c++ - char* 和 new 的一些错误

标签 c++ object pointers memory

我有相同的代码:

.hpp 文件:

class CConsoleModel
{
char* ParametersBuffer;

...

public:
CConsoleModel() ;  // - basic constructor;
~CConsoleModel() ; // -basic destructor
char *DeterminationParameter(std::string _command, int _parametersize);
...
};

.cpp 文件:

char *CConsoleModel::DeterminationParameter(std::string _command, int _parametersize)
{
  ParametersBuffer = new char[_parametersize];
  unsigned int HexValue;
 _command = _command.substr(_command.length() - (_parametersize*2),(_parametersize*2));
  //do conversion of the string to the required dimension (_parametrsize):
  for (int i(0); i<_parametersize;i++)
  {
    std::stringstream CommandSteam;
    CommandSteam<< std::hex <<_command[2*i];
    CommandSteam<< std::hex <<_command[2*i +1];
    CommandSteam >> std::hex >> HexValue;
    ParametersBuffer[i] = static_cast<char> (HexValue);
  }
  return  ParametersBuffer;
}

程序生成,但运行时崩溃。

如果我更改 ParametersBuffer = new char[_parametersize]

char* ParametersBuffer = new char[_parametersize]

一切正常。 我该如何解决这个问题?

最佳答案

我们强烈建议使用 std::vector 而不是手动分配内存。

class CConsoleModel
{
    std::vector<char> ParametersBuffer;

ParametersBuffer.resize(_parametersize);

...

return &ParametersBuffer[0];

顺便说一句

std::stringstream CommandSteam;
    CommandSteam<< std::hex <<_command[2*i];
    CommandSteam<< std::hex <<_command[2*i +1];
    CommandSteam >> std::hex >> HexValue;

太可怕了,当你有个位数的值时将无法工作。尝试

HexValue = (_command[2*i] << 8) | _command[2*i+1];

关于c++ - char* 和 new 的一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18617922/

相关文章:

进行构造函数转换时 C++ 运算符重载

arrays - 尝试将对象映射器模型转换为数组

c - 如何根据数组在不同行中的升序和降序打印c中的数组?

C - 帮助理解指针

java - 使用 equals 获取 NullPointerException

c++ - 我如何对 condition_variable::wait 周围的包装器进行单元测试?

c++:有什么方法可以避免在每个成员函数之前键入类名?

java - 为什么 C++ 和 Java 中的构造函数调用需要显式类型参数?

python - python 对象什么时候成为垃圾收集的候选对象?

JavaScript - 如何访问对象数组中的特定值