当我用 g++ 编译这段代码时,它不会抛出任何错误,但在运行时它会抛出类似的错误 双自由或腐败(fasttop) 或 tcache_thread_shutdown():检测到未对齐的 tcache 块
#include <iostream>
#include <thread>
#include <vector>
#include <curl/curl.h>
#include <fstream>
#include "arguments.cpp"
using namespace std;
int main(int argc, char* argv[]) {
const int THREAD_BATCH_SIZE = 100; // set the batch size
string userurl;
string wordlistfile;
arguments(argc, argv, &userurl, &wordlistfile);
std::vector<std::thread> threads;
int count = 0;
ifstream wordlistcount(wordlistfile);
string comurl = "";
string word;
while(getline(wordlistcount, word)) {
count++;
}
ifstream wordlist(wordlistfile);
for (int i = 1; i <= count; i++) {
if ((i - 1) % THREAD_BATCH_SIZE == 0) {
threads.emplace_back([&] { // creates and starts a thread
CURL* curl = curl_easy_init(); // initialize a new CURL object for each thread
curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
CURLcode res;
long http_code;
char *url = NULL;
for (int j = 1; j <= THREAD_BATCH_SIZE; j++) {
getline(wordlist, word);
comurl = userurl + word;
curl_easy_setopt(curl, CURLOPT_URL, comurl.c_str());
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0);
res = curl_easy_perform(curl);
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url); //CURLINFO_EFFECTIVE_URL
string color;
if (http_code < 200) {color = "\033[1;34m"; /* yellow */}
else if (http_code < 300) {color = "\033[1;32m"; /* green */}
else if (http_code < 400) {color = "\033[1;33m"; /* blue */}
else if (http_code < 500) {color = "\033[1;35m"; /* purple */}
else if (http_code < 600) {color = "\033[1;31m"; /* red */}
if (http_code != 0 && http_code != 404 && url != NULL) {
cout << color << http_code << " \033[0;97m /" << url << endl;
}
}
curl_easy_cleanup(curl); // cleanup the CURL object after processing the thread batch
});
}
}
for (auto& t : threads) { // wait for all threads to finish
t.join();
}
return 0;
}
我预计这个程序会向服务器发送许多请求以检查页面是否存在(出于道德目的的目录暴力破解)
getline(wordlist, word);
看起来这一行被多个执行线程执行。多个执行线程似乎试图从同一个输入流读取到
word
.
C++ 库中的所有类都不是线程安全的,包括
word
,一个被多个执行线程覆盖的对象。
这是未定义的行为。
comurl = userurl + word;
comurl
也是单个对象,在 main 中实例化,多个执行线程试图在这里修改,互相踩踏,并创建更多未定义的行为。
在显示的代码中可能有更多未定义行为的实例,我在这一点上停止分析。