我正在使用Borland Builder C++。我有一個內存泄漏,我知道它必須是因爲我創建的這個類,但我不知道如何解決它。請看我的代碼 - 任何想法將不勝感激!類中的指針垃圾,C++
這裏的.h文件:
#ifndef HeaderH
#define HeaderH
#include <vcl.h>
#include <string>
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());
}
現在,當我使用類爲主,基本上我只是創建一個指針:
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不包含所期望的內容,而且通常只是垃圾。我已經閱讀了很多關於內存泄漏和指針的問題,但是我對編程還是很陌生的,而且其中一些非常混亂。任何建議將是神話般的!
爲什麼人們低估了這一點?對我來說這似乎是一個合法的問題。我在這裏錯過了什麼嗎? – 2008-10-02 17:17:54