我正在使用Borland Builder C++.我有一个内存泄漏,我知道它必须是因为我创建的这个类,但我不知道如何解决它.请看我的代码 - 任何想法将不胜感激!
这是.h文件:
#ifndef HeaderH #define HeaderH #include#include using std::string; class Header { public: //File Header char FileTitle[31]; char OriginatorName[16]; //Image Header char ImageDateTime[15]; char ImageCordsRep[2]; char ImageGeoLocation[61]; NitfHeader(double latitude, double longitude, double altitude, double heading); ~NitfHeader(); void SetHeader(char * date, char * time, double location[4][2]); private: void ConvertToDegMinSec (double angle, AnsiString & s, bool IsLongitude); AnsiString ImageDate; AnsiString ImageTime; AnsiString Latitude_d; AnsiString Longitude_d; double Latitude; double Longitude; double Heading; double Altitude; };
这是一些.cpp文件:
void Header::SetHeader(char * date, char * time, double location[4][2]){ //File Header strcpy(FileTitle,"Cannon Powershot A640"); strcpy(OperatorName,"Camera Operator"); //Image Header //Image Date and Time ImageDate = AnsiString(date); ImageTime = AnsiString(time); AnsiString secstr = AnsiString(ImageTime.SubString(7,2)); AnsiString rounder = AnsiString(ImageDate.SubString(10,1)); int seconds = secstr.ToInt(); //Round off seconds - will this be necessary with format hh:mm:ss in text file? if (rounder.ToInt() > 4) { seconds++; } AnsiString dateTime = ImageDate.SubString(7,4)+ ImageDate.SubString(4,2) + ImageDate.SubString(1,2) + ImageTime.SubString(1,2) + ImageTime.SubString(4,2) + AnsiString(seconds); strcpy(ImageDateTime,dateTime.c_str()); //Image Coordinates Representation strcpy(ImageCordsRep,"G"); //Image Geographic Location AnsiString lat; AnsiString lon; AnsiString locationlat_d; AnsiString locationlon_d; AnsiString corner; for (int i = 0; i < 4; i++){ ConvertToDegMinSec(location[i][0],lat,false); ConvertToDegMinSec(location[i][1],lon,true); if(location[i][0] < 0){ locationlat_d = 'S'; ConvertToDegMinSec(-location[i][0],lat,false); }else if(location[i][0] > 0){ locationlat_d = 'N'; }else locationlat_d = ' '; if(location[i][1] < 0){ locationlon_d = 'W'; ConvertToDegMinSec(-location[i][1],lon,true); }else if(location[i][1] > 0){ locationlon_d = 'E'; }else locationlon_d = ' '; corner += lat + locationlat_d + lon + locationlon_d; } strcpy(ImageGeoLocation,corner.c_str()); }
现在,当我在main中使用该类时,基本上我只是创建一个指针:
Header * header = new Header; header->SetHeader(t[5],t[6],corners->location); char * imageLocation = header->ImageGeoLocation; //do something with imageLocation delete header;
其中corner-> location是来自另一个类的字符串,而t [5]和t [6]都是字符串.问题是imageLocation不包含预期的内容,通常只是垃圾.我已经阅读了很多关于内存泄漏和指针的内容,但我对编程仍然很陌生,其中一些非常令人困惑.任何建议都很棒!!
我担心这里有很多问题.
对于初学者char ImageCordsRep[1];
不起作用...字符串总是以空值终止,所以当你这样做时, strcpy(ImageCordsRep,"G");
你会溢出缓冲区.
在构造函数中使用null终止所有字符串缓冲区也是一种好习惯,因此它们始终是有效的字符串.
更好的方法是使用字符串类而不是char数组,或者至少使用'strncpy'来防止缓冲区溢出,如果传入的字符串大于您的预期.