簡體   English   中英

為什么我的函數給我“變量'url'周圍的堆棧已損壞。”錯誤?

[英]Why does my function gives me “Stack around the variable 'url' was corrupted.” error?

我有一個功能,可以從參數中給出的字符串中下載我的網站(完全字符串是url的結尾)。 這讓我失敗了

變量“ url”周圍的堆棧已損壞。

我的代碼:

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方法和固定大小的數組xprintf 我不熟悉TCHARTEXT (Windows事物),但是您可以執行以下操作:

std::wstring url;

url = std::wstring(TEXT("https://www.wordnik.com/words/")) + sw1 + TEXT("/");

wsprintf進入url范圍之外時,您正在寫。

而是這樣做(用於常規格式)

std::wostringstream urlstream;
urlstream << TEXT("https://www.wordnik.com/words/") << sw1 << TEXT("/"); 
std::wstring url = urlstream.str();

或(更簡單)

std::wstring url = std::wstring(TEXT("https://www.wordnik.com/words/")) + sw1 + TEXT("/");

您正在大量復制變量-據我所知,您可以將代碼縮減為:

    std::wstring w_word(word.begin(), word.end());
    std::wstring url = std::wstring(TEXT("https://www.wordnik.com/words/")) + w_word + TEXT("/");
    TCHAR currentpath[MAX_PATH];
    GetCurrentDirectory(MAX_PATH, currentpath);
    std::wstring path = std::wstring(currentpath) + TEXT("\\wordnik\\") + w_word + TEXT(".txt");
    HRESULT res = URLDownloadToFile(NULL, url.c_str(), path.c_str(), 0, NULL);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM