调用 free 会导致程序抛出异常
当我偶然发现以下问题时,我正在做作业。我应该使用 C 语言和 Windows API 函数创建一个简单的多线程应用程序。每个线程都会运行一个简单的任务,所以我决定回收一些我做过的旧东西。
我有一个头文件:
和一个源文件:
然后在 main 中,我进行以下调用:
LoadPoem();
ProcessPoem();
SavePoem();
LoadPoem 打开包含原始内容的文件,为输入分配一个缓冲区(变量loadPoemBuffer)并将文件中的文本存储在其中。然后,ProcessPoem 为更改后的版本分配一个缓冲区(变量processedPoemBuffer),并通过重复调用strtok 来填充它。然后它释放loadedPoemBuffer并结束。 到目前为止,一切都很好。 当我调用 SavePoem() 时,问题出现了,它正确保存了数据,但是当它结束时,它调用 free(processedPoemBuffer) 并抛出异常 - 堆损坏。我似乎无法理解为什么。在我看来,它执行的操作与之前的 ProcessPoem 完全相同,但该功能不会失败。
有人可以向我解释一下吗?提前致谢。
I was doing my homework when I stumbled upon the following problem. I should create a simple multi-threaded application using in C and using Windows API functions. Each thread would run a simple task, so i have decided to recycle some older stuff I did.
I have a header file:
And a source file:
Then in main, I make the following call:
LoadPoem();
ProcessPoem();
SavePoem();
LoadPoem opens up the file containing the original, allocates a buffer for input (variable loadedPoemBuffer) and stores the text from the file in it. ProcessPoem then allocates a buffer for the altered version (variable processedPoemBuffer) and fills it by repeatedly calling strtok. Then it frees loadedPoemBuffer and ends.
So far so good.
The problem emerges when I call SavePoem(), it correctly saves the data, but when it ends, it calls free(processedPoemBuffer) and throws an exception - corrupted heap. I can't seem to understand why. It seems to me that it does exactly the same operation as ProcessPoem before it, yet that function does not fail.
Can somebody please explain it to me? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
processedPoemBuffer 似乎是 LPWSTR,这意味着您的数据是 Unicode。然后调用 _tcscat_s ,如果您正在为 Unicode 构建,则需要字符数,而不是字节数。您需要将输入文件大小除以 _tcscat_s 缓冲区长度参数的 WCHAR 大小。
processedPoemBuffer appears to be LPWSTR which means your data is Unicode. Then you call _tcscat_s which, if you are building for Unicode expects the number of characters, not bytes. You need to divide your input file size by the size of a WCHAR for the _tcscat_s buffer length argument.
free
中的异常意味着您使用不是malloc
结果的内容来调用它。使用 NULL 初始化您的processedPoemBuffer
并在free
处检查它:Exception in
free
means that you call it with something that is not a result of amalloc
. Init yourprocessedPoemBuffer
with NULL and check it atfree
: