随着学校练习的发展,我正在制作一个程序,从程序执行的位置开始,在每个子文件夹中写入一个文件。因此,有一个递归函数和另一个函数在其中调用,它写入文件。
如果我执行此操作,我将在第二次写入文件时(在第一个子文件夹中,当我创建ofstream时)出现“Exitedwithcode=3221226356”错误.仅在调试时才使用。经过一些实验,我删除了递归调用,并将文件写入所有主目录。除了输入变量(char*)之外,没有数组,导致内存泄漏的原因是什么?
这是代码:
#include <dirent.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <time.h>
#include <limits.h>
const char * separator_char() {
#ifdef _WIN32
return "\\";
#else
return "/";
#endif
}
void createCopy(const char * path) {
const char * separator = separator_char();
char * file_name_path = strdup(path);
strcat(file_name_path, separator);
printf("Writing Roberto.txt...\n");
strcat(file_name_path, "Roberto.txt");
std::ofstream dst(file_name_path, std::ios::binary | std::ofstream::trunc); -- ERROR HERE
dst << "test";
printf("Wrote %s\n", file_name_path);
dst.close();
}
void multiply(const char * path) {
const char * separator = separator_char();
char * path_2 = strdup(path);
strcat(path_2, separator);
DIR * dir = opendir(path);
struct dirent * entry = readdir(dir);
while (entry != NULL) {
if (strcmp(entry -> d_name, ".") != 0 && strcmp(entry -> d_name, "..") && entry -> d_type == DT_DIR) {
char * path_3 = strdup(path_2);
strcat(path_3, entry -> d_name);
printf("%s\n", path_3);
createCopy(path_3);
multiply(path_3);
}
entry = readdir(dir);
}
closedir(dir);
}
int main(int argc, char ** argv) {
const char * PATH = ".";
multiply(PATH);
getchar();
return 0;
}
发布于 2022-11-28 11:20:52
这两行可能是一个问题:
char * file_name_path = strdup(path);
strcat(file_name_path, separator);
strdup
调用为要复制的字符串分配足够的内存,而不是多一个字节。
这意味着strcat
调用将导致程序写入分配内存的边界,从而导致未定义的行为(以及堆损坏)。
一个可能的C类解决方案是使用snprintf
函数来构造您的字符串。它可以与空指针目标字符串和零大小一起使用,然后返回字符串所需的字节数(不包括空终止符)。然后,您可以为字符串分配内存,并再次使用snprintf
来实际创建字符串。
或者,既然您正在编写C++,只需使用std::string
并根据需要追加即可。没有超出范围的问题,没有内存泄漏(你也有)。
考虑到您正在处理文件系统路径,请使用std::filesystem::path
:
void createCopy(std::filesystem::path const& path) {
auto file_name_path = path / "Roberto.txt";
std::ofstream dst(file_name_path, std::ios::binary | std::ofstream::trunc);
dst << "test";
}
https://stackoverflow.com/questions/74599752
复制相似问题