我有相同的代码:
.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/