why would freeing calloc'ed memory crash my VC6 project?

Compare these two largely identical functions. In the first, the memory for buff is allocated using _alloca. This works fine. In the second, calloc and free are used instead of _alloca. This crashes.

The weird thing is that I use the calloc/free technique in almost every other GMP wrapping function I have and they all work. Here they don't. Any ideas?


#define Z(x) mpz_t (x); mpz_init( (x) ); #define BUFF_SIZE (1024 * 32) BSTR __stdcall IBIGDIV(BSTR p1, BSTR p2 ) { USES_CONVERSION; Z(n1); Z(n2); Z(res); char * buff = (char *) _alloca( mpz_sizeinbase( res, 10 ) + 2 ); LPSTR sNum1 = W2A( p1 ); LPSTR sNum2 = W2A( p2 ); mpz_set_str( n1, sNum1, 10 ); mpz_set_str( n2, sNum2, 10 ); if ( mpz_sgn( n2 ) != 0 ) { mpz_div( res, n1, n2 ); mpz_get_str(buff, 10, res); } else { strcpy( buff, "-0" ); } BSTR bResult = _com_util::ConvertStringToBSTR( buff ); return bResult; }


#define Z(x) mpz_t (x); mpz_init( (x) ); #define BUFF_SIZE (1024 * 32) BSTR __stdcall IBIGDIV(BSTR p1, BSTR p2 ) { USES_CONVERSION; Z(n1); Z(n2); Z(res); char * buff = (char *) calloc( mpz_sizeinbase( res, 10 ) + 2, sizeof( char ) ); LPSTR sNum1 = W2A( p1 ); LPSTR sNum2 = W2A( p2 ); mpz_set_str( n1, sNum1, 10 ); mpz_set_str( n2, sNum2, 10 ); if ( mpz_sgn( n2 ) != 0 ) { mpz_div( res, n1, n2 ); mpz_get_str(buff, 10, res); } else { strcpy( buff, "-0" ); } BSTR bResult = _com_util::ConvertStringToBSTR( buff ); free( buff ); return bResult; }

-------------Problems Reply------------

Add logging and dump everything along the way to find what goes wrong. This is usually more efficient than trying to guess.

It may be unrelated, but this type of "works one way but not the other" often indicates a bug that just happens to squeak by in one situation but causes a fatal error in another.

If you suspect a memory overwrite may be occurring you could try allocating an extra 8-bytes in the buffer and writing 4-byte start and end sentinels which you then check for before freeing.

I once spent a week trying to figure out a similar thing. It was a buffer overrun that trashed the pointer so free was going off into the woods. Rational purify found the issue in a minute.

calloc could potentially return NULL if there's an error (such as lack of memory). I would recommend checking the result of any memory allocation function against NULL. If it is NULL, print a message and then exit(1).

_alloca returns stack memory, so stomping past the end of it may not necessarily overwrite something important. Writing past the end of a heap memory allocation will more likely overwrite something important.

Your code does nothing to ensure that the buffer is at least as big as res would be formatted to after dividing n1 by n2 (or vice versa, as I don't know what the actual function does); it only ensures that it has enough memory for an initialiazed res, which is probably 1. If n1/n2 has more digits than that, welcome to crashville.

@johnny pointed out something rather embarrassing, which necessitated a rewrite of the code. (Here's where being able to tick a comment would be useful.)

BSTR __stdcall IBIGDIV(BSTR p1, BSTR p2 ) {


char * buff;

LPSTR sNum1 = W2A( p1 );
LPSTR sNum2 = W2A( p2 );

mpz_set_str( n1, sNum1, 10 );
mpz_set_str( n2, sNum2, 10 );

if ( mpz_sgn( n2 ) != 0 ) {
mpz_div( res, n1, n2 );
buff = (char *) calloc( mpz_sizeinbase( res, 10 ) + 2, sizeof( char ) );
mpz_get_str(buff, 10, res);
} else {
buff = (char *) calloc( 3, sizeof( char ) );
strcpy( buff, "-0" );

BSTR bResult = _com_util::ConvertStringToBSTR( buff );
free( buff );
return bResult;

In the previous incarnations, the memory was being allocated according to the value of res at the point in the code where it contained zero. Thus I was trying to calloc zero bytes and free didn't like it. In the above code, res actually contains something that mpz_sizeinbase can work with.

Category:visual c++ Views:1 Time:2009-03-04

Related post

  • XCode heapshots non-objects increases causing memory crash 2012-04-21

    I have an app running on iPAD. Pretty complex one I would say. The main issue I am facing now is the memory crash. After going through several discussion threads, I could not figure out how to resolve it. All my memory leaks are fixed. While monitori

  • Can the try-catch mechanism be used to avoid memory crashes? 2010-09-10

    I am really interested to know that, Is it possible that using try ... catch mechanism, we can avoid memory crash of our application ... ?? Let say the program part that we are expecting a chance of memory leak is kept under try...catch block, if the

  • Memory crashes in iOS with real memory usage only at 5megs 2010-10-27

    I have been hunting down memory leaks for some time in my app. As of right now, as I flip back and forth between two views while watching the memory monitor instrument, the real memory fluctuates between 5 and 6 megs. This is all fine -- as far as I

  • didReceiveMemoryWarning not being called before memory crash 2011-05-04

    I'm loading a couple of large csv files when my app loads for the first time and this works fine on the simulator but when running on my phone it crashes about 30% through with the message 'Program received signal "0"' which implies a memory crash. H

  • Examples of forcing freeing of native memory direct ByteBuffer has allocated, using sun.misc.Unsafe? 2011-12-11

    JDK provides abillity to allocate so-called direct ByteBuffers, where memory is allocate outside of Java heap. This can be beneficial since this memory is not touched by garbage collector, and as such does not contribute to GC overhead: this is a ver

  • Memory Crash Dump File (BSOD, Product 768_1) 2012-09-30

    I am at a loss as to how to resolve this issue. I have run memory checks, even re-seated the RAM cards, but to no avail. When trying to shut down the computer, I encounter a BSOD with a memory crash dump that soon goes to a login screen. I am unable

  • BSOD, memory crash dumps... 2014-10-15

    I have an AMD Phenom II X4 3.5GHz, ATI Radeon HD 3300 graphics card, 2GB Ram, with Win7 Professional 32 bit. I am constantly getting BSOD, from what I can tell memory crash dump. How can I fix this problem? Thank you in advance for your help --------

  • Out-Of-Memory crash on iOS, but memory consumption is at 20MB 2015-01-26

    I am experiencing out-of-memory crashed with my app on iOS on both iPhone 6 and 5s. I am sure that memory is the problem, because I receive memory warnings and also because of the crash log. In the app I do video processing and process around 400 ima

  • VS2010 Crashes closing specific project 2011-02-21

    I'm working on a "Website Project" (as opposed to an ASP.NET Web Application) which we received from another company as part of an acquisition. In general it works fine, however every time I close the project ("File" -> "Close Project" or just "Fi

  • Freeing dynamically allocated memory 2010-07-18

    In C++, when you make a new variable on the heap like this: int* a = new int; you can tell C++ to reclaim the memory by using delete like this: delete a; However, when your program closes, does it automatically free the memory that was allocated with

  • PHP Out of Memory - Crashes Apache? 2010-01-02

    I am running PHP version 5.3.0 and Apache: 2.2.11 When I run PHP scripts that consume a lot of memory (I think) - large loops etc. My Apache web server reports a crash?! [Sat Jan 02 00:51:30 2010] [notice] Parent: child process exited with status 255

  • Starting a C++ project. Should I worry about freeing dynamic allocated memory? 2010-04-27

    I am pretty proficient with C, and freeing memory in C is a must. However, I'm starting my first C++ project, and I've heard some things about how you don't need to free memory, by using shared pointers and other things. Where should I read about thi

  • iPhone: Low memory crash 2010-05-08

    Once again I'm hunting memory leaks and other crazy mistakes in my code. :) I have a cache with frequently used files (images, data records etc. with a TTL of about one week and a size limited cache (100MB)). There are sometimes more then 15000 files

  • Freeing of allocated memory in Solaris/Linux 2010-06-01

    I have written a small program and compiled it under Solaris/Linux platform to measure the performance of applying this code to my application. The program is written in such a way, initially using a sbrk(0) system call, I have taken base address of

  • Objc memory crash with autorelase 2010-09-06

    I have been hunting all over my code and can't find the source of this crash: I am trying to decode an object with an NSKeyedUnarchiver and it crashes on it every time and says: *** __NSAutoreleaseFreedObject(): release of previously deallocated obje

  • iOS Low Memory Crash, but very low memory usage 2011-05-12

    This has been annoying me for a long time. My app runs taking up about 2.74MB of memory. That's fine. But then when it creates a UIWebView it goes up to around 5.87MB and proceeds to crash. Those are the values given under Live Bytes in Instruments w

  • iOS, iPhone, iPad: is slow loading a good strategy to avoid memory crashes? 2011-08-23

    This question is a follow-on to this other question. I have a game on the App Store that, only rarely, crashes when loading on iPad1. The game is resource-intensive and does indeed load up several large textures on start-up. A restart of the device m

  • Running in Windows CE from debugger causing eventual out-of-memory crash 2011-08-31

    I'm building a C# application for a Windows CE machine. The CE machine is talking to a serial device, and I'm using the SerialPort class. When I run the project from Visual Studio by right-clicking and deploying, it will run fine for fifteen to twent

  • How to resolve memory crash in iPhone 2011-09-30

    I'm creating an application which features having multiple animations. There are 50 pages and on each page there is a different animation and each animation uses many images. I'm using UIPresentModelViewController for presenting the views and am chan

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.206 (s). 11 q(s)