调用另一个对象(相同类)的功能后,私有成员的malloc内存将被覆盖

时间:2019-06-16 22:46:51

标签: c++ pointers malloc private-members

由与对象output相同类的对象input调用的函数似乎会导致意外行为,并覆盖对象input的{​​{1}}私有成员数据(指针地址保持不变)一样

对于对象mallocoutput*fileStr均为NULL,对于*p_file,两个点均指向数据
input / CASE1或每个CASE2的组合都将导致#ifdef数据被更改
如果input.fileStr数据本身被调用,则input.fileStrmalloc修饰(仅由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)

0 个答案:

没有答案