简体   繁体   English

用未分配的内存块编写的C ++文件

[英]C++ file written with unallocated memory block

I was programming and a coding mistake caused problems: 我在编程时,编码错误导致问题:

ofstream myFile;
myFile.open("/home/guido/ejemplo.XX",ios::out | ios::binary | ios::trunc);
...
buffer = new char;
delete (buffer); 
//write into file with accidentally freed memory block
myFile.close();
...
ifstream sameFile;
sameFile.open("/home/guido/ejemplo.XX",ios::in | ios::binary);
//Crashes at previous line

Now, if I commented all code lines before ifstream sameFile; 现在,如果我在ifstream sameFile;之前注释了所有代码行ifstream sameFile; , the execution of sameFile.open(...) wouldn't fail. ,执行sameFile.open(...)不会失败。 I'm not sure why does this happen. 我不确定为什么会这样。 Does the program keep track of files that were illegaly written/read? 程序是否跟踪非法写入/读取的文件? What did the write(...) and close() functions do in this problem? write(...)close()函数在此问题上做了什么?

It's not really possible to know exactly why it crashed the way it did. 真的不可能确切知道为什么它会崩溃。 That's why the C++ specifications calls it "undefined behavior": it is something that is outside of the language's definition. 这就是C ++规范将其称为“未定义行为”的原因:这是该语言定义之外的内容。 It might have executed correctly on some compilers/standard library implementations. 它可能已在某些编译器/标准库实现中正确执行。 It may have failed here due to memory corruption caused by the delete[] of a non-array pointer. 由于非数组指针的delete []引起的内存损坏,它可能在此处失败。

You could get a hardcore memory debugger (re: valgrind) to figure out the exact moment when the heap was corrupted. 您可以使用一个核心内存调试器(re:valgrind)来确定堆损坏的确切时间。 You might even see why the iostream object was damaged by this. 您甚至可能会看到为什么iostream对象被此损坏。 But it wouldn't really help any, because it might fail for entirely different reasons on another system. 但这并没有真正的帮助,因为它可能由于另一个系统上的完全不同的原因而失败。 Indeed, simply the act of introducing the memory debugger alone may change the behavior of where or when it fails. 确实,仅引入内存调试器的行为可能会改变其在何处或何时失败的行为。

The free isn't necessarily part of the problem, though that definitely makes it worse. 免费不一定是问题的一部分,尽管这肯定会使情况变得更糟。 You're overwriting the heap in one way or another when you read the file into the single byte buffer you allocated. 当您将文件读入分配的单字节缓冲区时,将以一种或另一种方式覆盖堆。 When you try to open another file, it requires access to the heap to allocate blocks of memory, and will often crash because the heap has been corrupted. 当您尝试打开另一个文件时,它需要访问堆才能分配内存块,并且由于堆已损坏而经常崩溃。 Particularly if you are in debug mode with memory checking on. 特别是在内存检查已打开的调试模式下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM