由与对象output
相同类的对象input
调用的函数似乎会导致意外行为,并覆盖对象input
的{{1}}私有成员数据(指针地址保持不变)一样
对于对象malloc
,output
和*fileStr
均为NULL,对于*p_file
,两个点均指向数据
input
/ CASE1
或每个CASE2
的组合都将导致#ifdef
数据被更改
如果input.fileStr
数据本身被调用,则input.fileStr
被malloc
修饰(仅由class1::open
调用),否则默认为NULL指针
标题
input
源代码
class class1
{
private:
FILE *p_file = NULL;
char *fileStr = NULL;
bool encrypt_step1();
public:
bool open(char *pathto);
bool create(char *pathto);
bool encrypt();
~class1();
};
bool sub_function(char *pathIN);
这似乎违反了内存访问,但是即使bool class1::open(char *pathto)
{
if (PathFileExistsA(pathto))
this->p_file = fopen(pathto, "rb+");
else
return 0;
if (!(this->p_file))
{
printf("Can't open\n");
return 0;
}
fseek(p_file, 0, SEEK_END);
long filesize = ftell(p_file);
fseek(p_file, 0, SEEK_SET);
this->fileStr = (char*)malloc(filesize+1);
this->fileStr[(fread(this->fileStr, 1, filesize, this->p_file))] = '\0';
return 1;
}
bool class1::create(char *pathto)
{
#ifdef CASE1
if (PathFileExistsA(pathto))
{
char pathtobak[MAX_PATH];
strcpy(pathtobak, pathto);
strcat(pathtobak, ".bak");
int i = 0;
char a[11];
if (PathFileExistsA(pathtobak))
{
while (1)
{
i++;
*a = '\0';
itoa(i, a, 10);
char *reset = pathtobak + strlen(pathtobak);
strcat(pathtobak, a);
if (!PathFileExistsA(pathtobak))
break;
*reset = '\0';
}
}
std::experimental::filesystem::copy_file(pathto, pathtobak);
}
#endif
#ifdef CASE2
this->p_file = fopen(pathto, "wb");
#endif
#ifndef NOERRORS
if (this->p_file == NULL)
return 0;
else
return 1;
#endif
}
class1::~class1()
{
if (this->fileStr)
{
free(this->fileStr);
this->fileStr = NULL;
}
if (this->p_file)
{
fclose(this->p_file);
this->p_file = NULL;
}
}
bool sub_function(char *pathIN)
{
class1 input;
input.open(pathIN);
input.encrypt();//omitted since this should be irrelevant
char pathOUT[MAX_PATH];
strcpy(pathOUT, pathIN);
char *OUText = pathOUT;
OUText += (strlen(pathOUT)-3);
*OUText = '\0';
strcat(pathOUT, "ext");
class1 output;
output.create(pathOUT);//bug here
char *next = input.get_fileStr();
...
}
只是简单地查找仅使用局部变量的重复文件仍然会导致意外的行为,因此我在查明原因时遇到了问题
最可能的原因是内存被标记为空闲,但我没有在析构函数之外对其进行分配,但是一旦进一步运行程序,一旦调用了CASE1
的析构函数,{ {1}}异常
源于input
free(input.fileStr)