我有一个函数,它应该从参数中给定的字符串下载一个网站(确切地说,字符串是 url 的结尾)。它让我失败
Stack around the variable 'url' was corrupted.
我的代码:
void download_wordnik(string word) {
string s1 = word;
std::wstring w_word_Tmp1(s1.begin(), s1.end());
wstring w_word1 = w_word_Tmp1;
std::wstring stemp1 = std::wstring(s1.begin(), s1.end());
LPCWSTR sw1 = stemp1.c_str();
TCHAR url[] = TEXT("https://www.wordnik.com/words");
wsprintf(url, TEXT("%s\/%s\/"), url, sw1);
LPCWSTR sw2 = stemp1.c_str();
TCHAR path[MAX_PATH];
GetCurrentDirectory(MAX_PATH, path);
wsprintf(path, TEXT("%s\\wordnik\\%s\.txt"), path, sw2);
HRESULT res = URLDownloadToFile(NULL, url, path, 0, NULL);
// Checking download
if(res == S_OK) {
printf("Ok\n");
} else if(res == E_OUTOFMEMORY) {
printf("Buffer length invalid, or insufficient memory\n");
} else if(res == INET_E_DOWNLOAD_FAILURE) {
printf("URL is invalid\n");
} else {
printf("Other error: %d\n", res);
}
}
我正在使用这个包括
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <Urlmon.h>
#include <regex>
#pragma comment(lib, "urlmon.lib")
using namespace std;
最佳答案
可能是因为您在 url
上复制的内容超过了它的容量,这导致了未定义的行为:
TCHAR url[] = TEXT("https://www.wordnik.com/words");// The size is `30` but ...
wsprintf(url, TEXT("%s\/%s\/"), url, sw1);// It copies more than `30` characters.
使用 std::wstring
方式,不要混淆 xprintf
方法和固定大小的数组。我不熟悉 TCHAR
或 TEXT
(Windows 东西),但你可以这样做:
std::wstring url;
url = std::wstring(TEXT("https://www.wordnik.com/words/")) + sw1 + TEXT("/");
关于c++ - 为什么我的函数给我 "Stack around the variable ' url' was corrupted."error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25365769/