2013-09-04 2 views
0

일부 버그가 내가 같은 코드가 있습니다의 char * 새로운

.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]에 변경하는 경우

. 이 문제를 어떻게 해결할 수 있습니까?

+1

문제가 '...'에 있다고 생각합니다. 가장 작은 코드 예제를 게시하여 컴파일하고 실행하여 문제를 보여줍니다. –

+2

확신 할 수있는 코드가 충분하지 않지만, [Rule of Three] (http://stackoverflow.com/questions/4172722), 'CConsoleModel'복사 및 같은 버퍼를 두 번 삭제하는 것이 좋습니다. 'std :: string' 또는'std :: vector '을'new'를 사용하는 것보다는 왜 사용합니까? –

+0

제 생각 엔 ParametersBuffer를 여러 번 삭제하거나 삭제 후에 사용하는 것 같습니다. 소멸자 ('~ CConsoleModel')에서 ParametersBuffer를 삭제합니까? – zennehoy

답변

2

수동 메모리 할당 대신 std::vector을 사용하는 것이 좋습니다.

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

ParametersBuffer.resize(_parametersize); 

...
return &ParametersBuffer[0]; 

이 BTW

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]; 
0

내 심령 디버깅 능력은 당신이 중 하나를 복사 생성자를 놓치고 말해 또는 할당 연산자를 복사 (또는 소멸자가 제대로 버퍼를 정리하지 않습니다)보십시오.

std::string을 사용하면 문제가 해결됩니다.

관련 문제