c++ - 为什么我的函数给我 "Stack around the variable ' url' was corrupted."error?

标签 c++ stack

我有一个函数,它应该从参数中给定的字符串下载一个网站(确切地说,字符串是 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 方法和固定大小的数组。我不熟悉 TCHARTEXT(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/

相关文章:

c++ - 如何从 argv[] 获取元素

c# - 使用 win32 DLL 部署 XBAP

c++ - 将 "this"指针转换为另一种类型不会违反严格的别名吗?

c++ - 通过引用而不是通过值从函数中获取对象

使用堆栈的 Java 迷宫资源管理器

c++ - 如何计算出文件中 "columns"的个数?

c++ - libstdc++ 并行模式快速排序的加速不佳

.net - .NET 堆栈与 Windows 堆栈

c++ - ret地址指向无处(?)

c - 主机上的本地用户如何使用缓冲区溢出攻击来获得对主机的根访问权限?