开发者

Call to free causes the program to throw an exception

开发者 https://www.devze.com 2023-04-12 14:39 出处:网络
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,

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:

http://pastebin.com/1aJFAwBg

And a source file:

http://pastebin.com/L127FGhG

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.


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.


Exception in free means that you call it with something that is not a result of a malloc. Init your processedPoemBuffer with NULL and check it at free :

void* processedPoemBuffer = NULL;
...
if (some_err) goto error;
... 
error:
if (processedPoemBuffer) // only delete checks for NULL
    free(processedPoemBuffer);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号