[英]Exception in Heap Memory Allocation
我正在使用Windows套接字將一些文件上傳到FTP服務器。 我正在搜索具有特定關鍵字的文件,如果文件名包含該關鍵字,則將其發送到服務器。 代碼是這樣的:
void FTPUpload(const char* path, const char* name)
{
SOCKET s1 = ConnectFTP("111.111.111.111", 21);
Receive(s1);
Send(s1, "USER user", true);
Receive(s1);
Send(s1, "PASS password", true);
Receive(s1);
Send(s1,"PWD", true);
Receive(s1);
Send(s1,"TYPE I", true);
Receive(s1);
Send(s1, "PASV", true);
char szString[1000];
Receive(s1, szString);
char szIP[40];
char* start = strchr(szString, '(' );
char* end = strchr(szString, ')' );
int num = end - start;
char str[30] = {'\0'};
strncpy( str, start + 1, num - 1 );
char* token = strtok( str , "," );
strcpy(szIP, "");
strcat(szIP, token);
strcat(szIP, ".");
token = strtok( NULL, "," );
strcat(szIP, token);
strcat(szIP, ".");
token = strtok( NULL, "," );
strcat(szIP, token);
strcat(szIP, ".");
token = strtok( NULL, "," );
strcat(szIP, token);
token = strtok( NULL, "," );
int intA = atoi(token);
token = strtok( NULL, "," );
int intB = atoi(token);
int port = (intA * 256) + intB;
sprintf(buf, "IP %s, Port %d", szIP, port);
//connect to FTP Server Data Connection
SOCKET s2 = ConnectFTP(szIP, port);
string command = "STOR " + string(name);
Send(s1, &command[0], true);
Receive(s1);
//Send the found file
long Begin;
long End;
char * block;
ifstream myfile;
myfile.open(path, ios::in | ios::binary);
Begin = myfile.tellg();
myfile.seekg(0,ios::end);
End = myfile.tellg();
unsigned long size = End - Begin;
int Div = (int)size / 1024;
int Mod = (int)size % 1024;
for (int i=0; i<Div; i++)
{
block = new char[1024];
myfile.seekg(i*1024);
myfile.get(block,1024+1);
Send(s2,block, false);
}
if (Mod != 0)
{
block = new char[Div];
myfile.seekg(Div*1024);
myfile.get(block,Mod+1);
Send(s2,block, false);
}
closesocket(s2);
myfile.close();
Receive(s1);
Send(s1, "QUIT", true);
Receive(s1);
closesocket(s1);
}
void FindFile()
{
string keyword = "key";
string path = "C:\\";
string ipath = path+"*";
WIN32_FIND_DATA file;
HANDLE search_handle = FindFirstFile(ipath.c_str(),&file);
if (search_handle != INVALID_HANDLE_VALUE)
{
do
{
string cpath = path + file.cFileName;
DWORD attr = GetFileAttributes(cpath.c_str());
if ((attr & (0x10)) != (0x10))
{
if ((cpath.find(keyword)) != (string::npos))
FTPUpload(cpath.c_str(), file.cFileName);
}
}
while(FindNextFile(search_handle,&file));
FindClose(search_handle);
}
}
當目錄中有兩個與關鍵字匹配的文件時,程序運行正常。 在第三個文件上,我在dbgheap.c中得到bad_alloc異常,即我在從堆分配和釋放內存方面遇到麻煩。 請幫助。
這是錯的
block = new char[1024];
myfile.seekg(i*1024);
myfile.get(block,1024+1);
塊為1024個字節,但get讀取1024個字符,然后附加一個'\\ 0'字符。 也許您打算使用read
not get
。
這是錯的
block = new char[Div];
myfile.seekg(Div*1024);
myfile.get(block,Mod+1);
塊是Div字節,但您讀取Mod字節。
可能對解決此問題沒有幫助,但請嘗試擺脫分配數組的習慣。 使用std::string
和std::vector
是更安全,更輕松的選擇。 例如
myfile.seekg(i*1024);
vector<char> block(1024);
myfile.read(&block[0],block.size());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.