繁体   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