Memory Leaks in JNI code

Hi,
I have written a small C++ code which will load a JDBC Driver and connect to the database.
The code initially Loads the JVM & than connects to the Database.
When i tested the code with Boundscheket I found a conciderable amount of memory leak & all of these are shown in jvm.dll, zip.dll & java.dll. Is this OK? Are there memory leaks in JNI?

Hi, Please go through the code & let me know if there are any memory leaks in this code. Boundchecker detects a considerable amount of memory leak :(
#include <windows.h>
#include <stdio.h>
#include <jni.h>
#include <conio.h>
#define INI_MAX_PROPERTY_VALUE 1024
#define JVMPATH "C:\\Java\\jdk1.5\\jre\\bin\\client\\jvm.dll"
#define JDBCDRIVER "-Djava.class.path=D:\\mysql-connector-java.jar";
#define CONNECTIONSTRING "jdbc:mysql://localhost:3306/test?user=root&password=root"
#define DRIVERCLASS "com/mysql/jdbc/Driver"
JavaVM *jvm = NULL;
unsigned long int jvmVersion = 0x00010004;
HINSTANCE lib_handle = NULL;
void fini() {
     jint res = jvm->DestroyJavaVM();
     printf ("Destroying JVM %d\n",res);
     if (lib_handle) {
          FreeLibrary(lib_handle);
          printf ("Deleted lib handle\n");
void init()
     char jvmPath[INI_MAX_PROPERTY_VALUE + 1];
     jint res = -1;
     JNIEnv *jniEnv = NULL;
     JavaVMInitArgs vm_args;
     JavaVMOption options[1];
     options[0].optionString = JDBCDRIVER;
     vm_args.version = jvmVersion;
vm_args.options = options;
vm_args.nOptions = 1;
vm_args.ignoreUnrecognized = JNI_TRUE;
     memset(jvmPath, '\0', INI_MAX_PROPERTY_VALUE + 1);
     strcpy(jvmPath,JVMPATH);
     printf("Loading dll from %s\n",jvmPath);
     lib_handle = LoadLibrary(jvmPath);
     if (!lib_handle)
          printf("Error during LoadLibrary\n");
          return;
     printf("JVM dll Loaded Sucessfully\n");
     jint (__stdcall JNI_CreateJavaVM)( JavaVM*, void**, void*);
     JNI_CreateJavaVM = (jint (__stdcall *)(JavaVM**, void**, void*))GetProcAddress(lib_handle, "JNI_CreateJavaVM");
     if (NULL != JNI_CreateJavaVM)
          res = (JNI_CreateJavaVM)( &jvm, (void**)&jniEnv , &vm_args);
     if ( res < 0 ) {
          printf("Unable to create JVM\n");
     } else {
          printf("JVM Created Succesfully\n");
void printException(JNIEnv *jniEnv) {
     jthrowable exceptionHandle = jniEnv->ExceptionOccurred();
     if ( exceptionHandle == NULL )
          return;
     /* Clear the exception from the enviroment*/
     jniEnv->ExceptionClear();
     /* Obtain the JavaException object to get its details */
     jclass jThrowableClass = jniEnv->GetObjectClass(exceptionHandle);
     if ( jThrowableClass == NULL ) {
          if (exceptionHandle)
               jniEnv->DeleteLocalRef(exceptionHandle);     
          exceptionHandle = NULL;
          return ;
     printf("\n*****----- Java Error Message is -----*****\n");
     jmethodID midMessage = jniEnv->GetMethodID( jThrowableClass, "toString", "()Ljava/lang/String;" );
     if ( midMessage == NULL ){
          if (exceptionHandle)
               jniEnv->DeleteLocalRef(exceptionHandle);
          if (jThrowableClass)
               jniEnv->DeleteLocalRef(jThrowableClass);
          exceptionHandle = NULL;
          jThrowableClass = NULL;
          return;
     jstring jstrRet = (jstring)jniEnv->CallObjectMethod(exceptionHandle,midMessage);
     if ( jstrRet == NULL ){
          if (exceptionHandle)
               jniEnv->DeleteLocalRef(exceptionHandle);
          if (jThrowableClass)
               jniEnv->DeleteLocalRef(jThrowableClass);
          exceptionHandle = NULL;
          jThrowableClass = NULL;
          return;
     jboolean flg;
     const char *pExceptionStr = jniEnv->GetStringUTFChars(jstrRet, &flg);
     if ( flg == JNI_TRUE ) {
          printf("%s",pExceptionStr);
          jniEnv->ReleaseStringUTFChars(jstrRet, pExceptionStr);
     if (exceptionHandle)
          jniEnv->DeleteLocalRef(exceptionHandle);
     if (jThrowableClass)
          jniEnv->DeleteLocalRef(jThrowableClass);
     if (jstrRet)
          jniEnv->DeleteLocalRef(jstrRet);
     exceptionHandle = NULL;
     jThrowableClass = NULL;
     jstrRet = NULL;
     printf("\n**************---------End of Java Error Message ************\n");
     return;
void connect() {
     jint res = -1;
     JNIEnv *jniEnv = NULL;
     jclass clsDriver = NULL;
     jmethodID colnstructorDriver = NULL;
     jmethodID methodConnect = NULL;
     jobject objectDriver = NULL;
     jobject objectConnection = NULL;
     jstring jConnectionString = NULL;
     printf("Getting the Enviroment\n");
     jint isPresent = jvm->GetEnv((void **)&jniEnv, jvmVersion );
     if (isPresent == JNI_EDETACHED || jniEnv == NULL) {
          printf("Could not get JNI Env for current thread");
return;
     printf("Creating Instance of Driver\n");
     clsDriver = jniEnv->FindClass(DRIVERCLASS);
     colnstructorDriver = jniEnv->GetMethodID(clsDriver, "<init>", "()V");
     objectDriver = jniEnv->NewObject( clsDriver, colnstructorDriver );
     printf("Created Instance of Driver\n");
     printf("Connecting to the Database\n");
     methodConnect = jniEnv->GetMethodID(clsDriver, "connect", "(Ljava/lang/String;Ljava/util/Properties;)Ljava/sql/Connection;");
     jConnectionString = jniEnv->NewStringUTF(CONNECTIONSTRING);
     objectConnection = jniEnv->CallObjectMethod(objectDriver, methodConnect, jConnectionString, NULL);
     if (objectConnection == NULL) {
          printException(jniEnv);
          printf("Unable to Connect\n");
     else
          printf("Connection Done\n");
     //Releasing all the memory used....
     if (objectConnection)
          jniEnv->DeleteLocalRef(objectConnection);
     if (jConnectionString)
          jniEnv->DeleteLocalRef(jConnectionString);
     if (objectDriver)
          jniEnv->DeleteLocalRef(objectDriver);
     if (clsDriver)
          jniEnv->DeleteLocalRef(clsDriver);
     objectConnection = NULL;
     jConnectionString = NULL;
     objectDriver = NULL;
     clsDriver = NULL;
int main() {
     printf ("Starting...\n");
     init();
     connect();
     fini();
     getch();
}

Similar Messages

  • Fixing Memory leaks in C code accessed via JNI

    Hi,
    I am working on an JNI interface between Java and legacy C code and I have problems with controlling the Memory inside the C code. In my application, I call many times from Java the C routines. In the C routines, memory is allocated but in a rather unclear and sloppy
    way. Not all memory is return after the C code finishes and I cannot go inside the code and release the memory block using free(). As a consequence, after a couple of runs all memory is consumed. Nevertheless, I know that all memory allocated in the C program should be available again after the C routine has finished.
    Is there a trick available that, for example, I can release all claimed memory by the C program before returning to Java, so the next time a C routine is called from Java, all free memory is again available for the C routine?
    Perhaps unloading the DLL and reloading the DLL before each C routine (how to do?).
    Or keeping track of the memory pointer before entering the C code and force it back to that position (freeing the claimed memory) after finishing the C code part (how to do?).

    Presumably you know that the correct way is to fix the C code?
    Maybe or mabe not...thinking out loud here...(and you need to check everything I say, since I am not doing the research, just pulling it out of my head.)
    The only way to do what you want is to dig deep, deep into the OS and compiler.
    Each process on the OS allocates a stack and a heap (this is not the java heap) to the process when it starts.
    You could then take a snap shot of the heap before starting. Then on exit you would free anything that wasn't in use when you started.
    However, your java app uses the same heap, so if you have any threads then it won't work. But you always have more than one thread, for instance the garbage collector. You could of course hack the jvm source to suspend all the threads (C suspension not java) to solve that problem.
    But you can't make any java method calls in your C code without doing the snap shot thing again. And I would bet that comparing the post and pre snap shots is going to take a while.
    Alternatively I do know that dlls use (or maybe used to use) either their own heap or their own stack. If it is the heap then at least the time problem won't be as much.
    I think there is also a way to replace the heap. This might be easy or hard. And either way it is probably dangerous. But if you did that then you would never have to worry about the snap shot comparison. Just throw away the new heap when you are done (give it back to the OS.)
    You might want to really look at that C code to. C programmers tended to use global variables a lot and initialize them in routines like
    static void* mylocal =0;
    void doit() { if (!mylocal) mylocal = malloc(sizeof(something)); }
    And if that occurs anywhere then switching heaps or deleting snap shots is probably not going to work.

  • Possible memory leak in C++ code

    Hello,
    I have a Java application that calls through JNI, functions in a C++ dll that use the GroupWise API (COM based). After the application creates a number of accounts in GroupWise the memory footprint of the java.exe process reaches ~1.5GB of RAM on a 32 bit Windows OS. After reaching this value, the C++ code no longer works, meaning that connecting to GroupWise fails. If I restart the application at this point everything starts to work until it reached ~1.5 GB again.
    I am suspecting that the problem might be caused by a memory leak. I have taken a dump of the java process with jmap and analyzed it with jhat. If I have not released an object in C++ code, would this object be visible in the dump i took of the java.exe process? The biggest consumer from what i have seen in the dump is class [B      20353-instances      33259261-bytes.
    Has anyone else tried to track a memory leak in a JNI application? How did you achive this task, what tools did you use?
    Thank you,
    Ionut Marin.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Has anyone else tried to track a memory leak in a JNI application? How did you achive this task, what tools did you use?You write a library in C/C++ only which does NOT use JNI which implements the functionality you want to achieve in your java application.
    You write a wrapper for that which excercises it completely including be able to run it in a loaded state.
    Then you buy/find a C/C++ profiling tool and run it on the wrapper.
    You write you JNI code such that the ONLY thing it does is interface between java and the library above. It doesn't impleent business logic nor work flow.

  • Detect memory leak in JNI so files for linux and Solaris

    I have to find the memory leaks in the JNI for solaris and linux but the issue is
    i need to find the leaks in the so files.I have solved the issues of leaks using Purify
    on windows but not getting appropriate support for linux. Any pointers to tools will help.I tried Valgrind on linux but it is not giving me the exact location of leak as in purify and also the support for purify is for 32 bit only.Valgrind is not showing any functions in .so files.JNI is not supported in Purify for Solaris? Please Help.

    amol28 wrote:
    I have to find the memory leaks in the JNI for solaris and linux but the issue is
    i need to find the leaks in the so files.I have solved the issues of leaks using Purify
    on windows but not getting appropriate support for linux. Any pointers to tools will help.I tried Valgrind on linux but it is not giving me the exact location of leak as in purify and also the support for purify is for 32 bit only.Valgrind is not showing any functions in .so files.JNI is not supported in Purify for Solaris? Please Help.If you have written the JNI, the JNI itself (java calls, methods, etc) to be OS agnostic then it shouldn't matter. In that case you check the windows code (not jni), the linux code (not jni) and the jni code itself independent of each other.
    If you haven't made the JNI OS agnostic the question would be why not?

  • How to manage the memory within this JNI code

    This is a piece of JNI code that i had written..........
    i am calling these methods in a infinite loop to listen for changes......
    if a change has occured it shpuld get changed. other wise not....
    But the memory is allocated 4 bytes every second.... even if the user doesnt makes a change....... ( memory increases with TIME....... )
    How to get rid of this problem
    Please Help!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #include <jni.h>
    #include "ParameterClass.h"
    #include <stdio.h>
    #include <scrpcdll.h>
    const char *NetAddr = "";
    const char *str = NULL;
    int sp= 0;
    double value= 0;
    jsize doubleLen = 0;
    jsize strLen = 0;
    int val=0;
    int i= 0 ;
    jdouble *body = NULL;
    const char *name = NULL;
    jstring *string = NULL;
    const char *tableStr = NULL;
    int sp1 = 0;
    double value1 = 0;
    JNIEXPORT jdouble JNICALL
    Java_ParameterClass_IdentificationValue(JNIEnv *env, jobject obj,jstring parameterName,jdouble parameterValue)
         if(SC_ConnectToSoftcar(NetAddr))
              str = (*env)->GetStringUTFChars(env,parameterName,NULL);
              sp = SC_AddVari(str, 6, "M");
              SC_Set(sp,parameterValue);
              (*env)->ReleaseStringUTFChars(env,parameterName,str);
              (*env)->ReleaseStringUTFChars(env,parameterName,NULL);
              value = SC_Get(sp);
         (*env)->DeleteLocalRef(env,parameterName);
         return value;
    JNIEXPORT void JNICALL
    Java_ParameterClass_OnlineValue(JNIEnv *env1,jobject obj1,jobjectArray str,jdoubleArray doArr)
         if(SC_ConnectToSoftcar(NetAddr))
              doubleLen = (*env1)->GetArrayLength(env1, doArr);
              strLen = (*env1)->GetArrayLength(env1,str);
              body = (*env1)->GetDoubleArrayElements(env1,doArr,NULL);
              for(i = 0; i < doubleLen; i++)
                   *string = (jstring)(*env1)->GetObjectArrayElement(env1,str,i);
                   name = (*env1)->GetStringUTFChars(env1,*string,NULL);
                   val = SC_AddVari(name, 6, "revs");
                   SC_Set(val,body);
                   (*env1)->ReleaseStringUTFChars(env1,*string,name);
                   (*env1)->ReleaseStringUTFChars(env1,*string,NULL);
              (*env1)->ReleaseDoubleArrayElements(env1,doArr,body,0);
              (*env1)->DeleteLocalRef(env1, *string);
         SC_DisconnectFromSoftcar();
         return;

    Hai,
    Thanks for your comments.......
    In Java i call the JNI methods inside a Infinite loop...
    when i comment this Infinite loop then the memory doesnt Increase at all.....
    but i cannot comment since i need a functionality to execute through JNI.....
    so if i uncomment this Infinte loop then i get a Probelm.........
    This is the JAVA CODE which calls JNI CODE:::::::::::::::::::::
    while(loopForever)
         streamWrite();
         System.gc();
    public void streamWrite()
    // Getting the Parameter Value from the Softcar
         for(i = 0; i < newparameterArray.length; i++)
              newparameterArray[i] = valueClass.returnIdentificationValue(prefix+parent.parameterName);
              System.gc();
    /*Checking the Array of values: Checking which value of the Array has changed in Softcar      Checking for the Elements of the Array which had been changed by the User if the change is made then Updating to the ASAP-3 Server.........*/
         if(Arrays.equals(parameterArray,newparameterArray) == true)
              for(i = 0; i < newparameterArray.length; i++)
              newparameterArray[i] = valueClass.returnIdentificationValue(prefix+parent.parameterName[i]);
              System.gc();
         else{
              for(i = 0; i < newparameterArray.length; i++)
                   if(parameterArray[i] != newparameterArray[i])
                        parameterArray[i] = newparameterArray[i];
                             parent.commandparameters.setapsparameters.parameterField.setText(parent.parameterName[i]);
                             parent.commandparameters.setapsparameters.parameterValueField.setText(Double.toString(newparameterArray[i]));
              try{
                   bos.write((byte[])parent.commandparameters.setapsparameters.setParameterArray());
                   bos.flush();
                   Thread.sleep(500);
                   readfromStream();
                   serverResponse();
              }catch(IOException exception){System.err.println(" Write Stream Exception" + exception.getMessage());}
              catch(InterruptedException ie){System.err.println(ie.getMessage());};
              //parameterArray[i] = newparameterArray[i];
              System.gc();
    //Getting the TableValue from Softcar.......
              for(j = 0; j < Integer.parseInt(parent.xDimension); j++)
                   newtableValueArray[j] = valueClass.returngetTableValue(arrayString[j]);
                   System.gc();
    //Comparing the Values ( whether the user has chaged the TableValue )
              if(Arrays.equals(tableValueArray,newtableValueArray) == true)
                   for(j = 0; j < newtableValueArray.length; j++)
                        newtableValueArray[j] = valueClass.returngetTableValue(arrayString[j]);
                        System.gc();
              else
                   for(j = 0; j < newtableValueArray.length; j++)
                        if((tableValueArray[j] != newtableValueArray[j]))
                             tableValueArray[j] = newtableValueArray[j];
                             parent.commandparameters.setlookupparameters.yindexField.setText(parent.yDimension);
                             parent.commandparameters.setlookupparameters.xindexField.setText(Integer.toString(j+1));
                             parent.commandparameters.setlookupparameters.valueField.setText(Double.toString(newtableValueArray[j]));
                             try{
                                  bos.write((byte[])parent.commandparameters.setlookupparameters.setlookupArray());
                                  bos.flush();
                                  Thread.sleep(500);
                                  readfromStream();
                                  serverResponse();
                             }catch(IOException exception){System.err.println(" Write Stream Exception" + exception.getMessage());}
                             catch(InterruptedException ie){System.err.println(ie.getMessage());};
                             System.gc();

  • Memory leak in xquery code in DbXml?

    While running a xml db which is update and xquery heavy, we are seeing the memory foot print grow to multiple gigs in a few minutes.
    One of the sample output from running it in valgrind is as follows.
    ==6847== 792,931,233 bytes in 4,695,090 blocks are still reachable in loss record 323 of 323
    ==6847== at 0x4A19007: malloc (in /usr/lib64/valgrind/amd64-linux/vgpreload_memcheck.so)
    ==6847== by 0x64BE0C5: BaseMemoryManager::allocate(unsigned long) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x554A0C0: xercesc_2_8::XMemory::operator new(unsigned long, xercesc_2_8::MemoryManager*) (in /usr/local/maui/lib/libxerces-c.so.28.0)
    ==6847== by 0x64E2BC8: xercesc_2_8::RefHash2KeysTableOf<int>::RefHash2KeysTableOf(unsigned, bool, xercesc_2_8::MemoryManager*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x64E181E: StaticAnalysis::StaticAnalysis(XPath2MemoryManager*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x61A7076: DbXml::SequentialScanQP::SequentialScanQP(DbXml::ImpliedSchemaNode::Type, DbXml::ImpliedSchemaNode*, DbXml::ContainerBase*, unsigned, XPath2MemoryManager*) (QueryPlan.hpp:160)
    ==6847== by 0x61A7136: DbXml::SequentialScanQP::copy(XPath2MemoryManager*) const (XPath2MemoryManager.hpp:175)
    ==6847== by 0x619474F: DbXml::QueryPlan::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (stl_vector.h:557)
    ==6847== by 0x618DC2E: DbXml::QueryPlan::createAlternatives(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (QueryPlan.cpp:128)
    ==6847== by 0x61CC1D5: DbXml::LevelFilterQP::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (LevelFilterQP.cpp:101)
    ==6847== by 0x61994A0: DbXml::QueryPlan::createReducedAlternatives(double, unsigned, DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (QueryPlan.cpp:157)
    ==6847== by 0x6182852: DbXml::StructuralJoinQP::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (StructuralJoinQP.cpp:260)
    ==6847== by 0x61994A0: DbXml::QueryPlan::createReducedAlternatives(double, unsigned, DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (QueryPlan.cpp:157)
    ==6847== by 0x61B2C13: DbXml::NodePredicateFilterQP::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (NodePredicateFilterQP.cpp:290)
    ==6847== by 0x61994A0: DbXml::QueryPlan::createReducedAlternatives(double, unsigned, DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (QueryPlan.cpp:157)
    ==6847== by 0x618258C: DbXml::StructuralJoinQP::applyConversionRules(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) (XPath2MemoryManager.hpp:202)
    ==6847== by 0x618355D: DbXml::ChildJoinQP::applyConversionRules(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) (ChildJoinQP.cpp:46)
    ==6847== by 0x619958D: DbXml::QueryPlan::createReducedAlternatives(double, unsigned, DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (stl_iterator.h:614)
    ==6847== by 0x61824FE: DbXml::StructuralJoinQP::applyConversionRules(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) (XPath2MemoryManager.hpp:202)
    ==6847== by 0x619958D: DbXml::QueryPlan::createReducedAlternatives(double, unsigned, DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (stl_iterator.h:614)
    ==6847== by 0x61B2C13: DbXml::NodePredicateFilterQP::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (NodePredicateFilterQP.cpp:290)
    ==6847== by 0x618DC2E: DbXml::QueryPlan::createAlternatives(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (QueryPlan.cpp:128)
    ==6847== by 0x61B25A0: DbXml::NodePredicateFilterQP::applyConversionRules(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) (XPath2MemoryManager.hpp:202)
    ==6847== by 0x619958D: DbXml::QueryPlan::createReducedAlternatives(double, unsigned, DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (stl_iterator.h:614)
    ==6847== by 0x618258C: DbXml::StructuralJoinQP::applyConversionRules(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) (XPath2MemoryManager.hpp:202)
    ==6847== by 0x618355D: DbXml::ChildJoinQP::applyConversionRules(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) (ChildJoinQP.cpp:46)
    ==6847== by 0x619958D: DbXml::QueryPlan::createReducedAlternatives(double, unsigned, DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (stl_iterator.h:614)
    ==6847== by 0x6182892: DbXml::StructuralJoinQP::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (StructuralJoinQP.cpp:264)
    ==6847== by 0x61CAF39: DbXml::BufferQP::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (XPath2MemoryManager.hpp:202)
    ==6847== by 0x6198964: DbXml::QueryPlan::chooseAlternative(DbXml::OptimizationContext&, char const*, bool) const (QueryPlan.cpp:291)
    ==6847== by 0x61CAD75: DbXml::BufferQP::createCombinations(DbXml::OptimizationContext&, std::vector<DbXml::QueryPlan*, std::allocator<DbXml::QueryPlan*> >&) const (BufferQP.cpp:230)
    ==6847== by 0x6198964: DbXml::QueryPlan::chooseAlternative(DbXml::OptimizationContext&, char const*, bool) const (QueryPlan.cpp:291)
    ==6847== by 0x61567BE: DbXml::QueryPlanOptimizer::optimizeQueryPlanToAST(DbXml::QueryPlanToAST*) (QueryPlanToAST.hpp:29)
    ==6847== by 0x66506E6: ASTVisitor::optimizeForTuple(ForTuple*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x665066A: ASTVisitor::optimizeTupleNode(TupleNode*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x664FF63: ASTVisitor::optimizeReturn(XQReturn*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x664F9B3: ASTVisitor::optimize(ASTNode*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x6650DBF: ASTVisitor::optimize(XQQuery*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x664F7A4: Optimizer::startOptimize(XQQuery*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x664F7A4: Optimizer::startOptimize(XQQuery*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x664F7A4: Optimizer::startOptimize(XQQuery*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x664F7A4: Optimizer::startOptimize(XQQuery*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x664F7A4: Optimizer::startOptimize(XQQuery*) (in /usr/local/maui/lib/libxqilla.so.4.0.1)
    ==6847== by 0x6079D98: DbXml::QueryExpression::QueryExpression(std::string const&, DbXml::XmlQueryContext&, DbXml::Transaction*) (ScopedPtr.hpp:41)
    ==6847== by 0x60D6A5B: DbXml::XmlManager::prepare(DbXml::XmlTransaction&, std::string const&, DbXml::XmlQueryContext&) (XmlManager.cpp:563)
    ==6847== by 0x60D6B70: DbXml::XmlManager::query(DbXml::XmlTransaction&, std::string const&, DbXml::XmlQueryContext&, unsigned) (XmlManager.cpp:581)
    Message was edited by:
    user626230

    This looks like a memory leak. Please correct me if I am wrong. Also, since the library uses a memory manager would'nt it be reported differently?
    They allocate a a new QueryPlan when they do a copy
    QueryPlan SequentialScanQP::copy(XPath2MemoryManager mm) const
    if(!mm) {
    mm = memMgr_;
    SequentialScanQP *result = new (mm) SequentialScanQP(nodeType_, isn_, container_, flags_, mm);
    result->nameid_ = nameid_;
    result->nsUriID_ = nsUriID_;
    result->cost_ = cost_;
    result->setLocationInfo(this);
    return result;
    Which is called from
    void QueryPlan::createCombinations(OptimizationContext &opt, QueryPlans &combinations) const
    combinations.push_back(copy(opt.getMemoryManager()));
    which is never freed here.
    void QueryPlan::createAlternatives(OptimizationContext &opt, QueryPlans &alternatives) const
    QueryPlans combinations;
    createCombinations(opt, combinations);
    // Generate the alternatives by applying conversion rules to the combinations
    for(QueryPlans::iterator it = combinations.begin(); it != combinations.end(); ++it) {
    (*it)->applyConversionRules(opt, alternatives);
    }

  • Possible memory leaks in the code , ASSERT messages in debug version !!!

    Hi,
    I have my Indesign C++ plugin running successfully in DEBUG and RELEASE versions of Indesign.
    But in Debug version, when I close my Indesign, I get a series of ASSERTS which I am not able to figure out why.
    Below is the list of ASSERT I am getting while closing Indesign(loaded with my plugin)
    Still have un-registered listener
    ..\..\..\source\components\csxs\CSXSPlugPlug.cpp (562)
    ASSERT 'fInitialized' in ..\..\..\source\components\csxs\CSXSPlugPlug.cpp at line 1027 failed.
    ~InstanceList(): 2 outstanding references to UID 421 (Class kTextStoryBoss).
    ..\..\..\source\components\database3\main\InstanceList.cpp (1928)
    ~InstanceList(): 1 outstanding references to UID 443 (Class kSBOSMgrIndexStorageBoss).
    ..\..\..\source\components\database3\main\InstanceList.cpp (1928)
    ~InstanceList(): 1 outstanding references to UID 420 (Class kFrameListBoss).
    ..\..\..\source\components\database3\main\InstanceList.cpp (1928)
    ~InstanceList(): 5 outstanding references to UID 1 (Class ShuksanPrefix + 1 (0x101)).
    ..\..\..\source\components\database3\main\InstanceList.cpp (1928)
    28 Outstanding Bosses!(Check file :QA:Logs:OutstandingBossLog.txt)
    c:\development\citius\source\private\foundation\InterfaceTrackingUtils.cpp (107)
    What changes do I need to make in my code to avoid these ASSERTS and is this something I should worry about?

    I tried to follow the instructions by copying the text file and restarting Indesign but then it failed immidiately.
    I have use InterfacePtr every where to get the reference of the boss I dont understand how these Outstanding Boss classes are remaining in my code.

  • Memory leak with SystemTray

    Hello,
    I just found a memory leak in my code caused by the SystemTray, but I don't know if that is me that misused SystemTray (I add a trayIcon, then remove it, then add an another one, and so on). I know how to get around that problem, but I don't know the origin of it (my code, java bug ?). So I made the following code reproducing that leak. If someone can give me idea or advice :-)
    class MyThread extends Thread {
      ReferenceQueue<?> referenceQueue;
      public MyThread(ReferenceQueue<?> referenceQueue) {
        this.referenceQueue = referenceQueue;
      @Override
      public void run() {
        System.out.println("Starting ...");
        try {
          while (true) {
            referenceQueue.remove();
            System.out.println("We release a TrayIcon");
        } catch (InterruptedException ex) {
          Logger.getLogger(MyThread.class.getName()).log(Level.SEVERE, null, ex);
    class MyPopup extends PopupMenu {
      static final int MAX = 1000000;
      Integer []toto = new Integer[MAX];
      public MyPopup() {
        for(int i = 0; i < MAX; i++)
          toto[i] = i;
    public class Main {
        public static void main(String[] args) {
          PopupMenu popup;
          ReferenceQueue referenceQueue = new ReferenceQueue();
          Vector<WeakReference>weakReference = new Vector<WeakReference>();
          MyThread myThread = new MyThread(referenceQueue);
          myThread.start();
          SystemTray tray = SystemTray.getSystemTray();
          TrayIcon trayIcon;
          File file = new File(<AN IMAGE HERE>);
          Image image;
          try {
            image = ImageIO.read(file);
            while(true) {
              popup = new PopupMenu();
              trayIcon = new TrayIcon(image, "Frame Title", popup);
              tray.add(trayIcon);
              tray.remove(trayIcon);
              weakReference.add(new WeakReference(trayIcon, referenceQueue));
          } catch (IOException ex) {
            Logger.getLogger(MyJFrame.class.getName()).log(Level.SEVERE, null, ex);
          } catch (AWTException e) {
              Logger.getLogger(MyJFrame.class.getName()).log(Level.SEVERE, null, e);
    }------------------------------------------- ADDED -----------------------------------
    P.S. :
    - the toto array in MyPopup is there in order to obtain quicker a OutOfMemory (OOM)
    - you may change your java parameter by fixing the allowed memory size in order to have a OOM quicker (-Xms30m -Xmx30m)
    - you must have an image in order to test this code (and set the path where <AN IMAGE HERE> is)
    - if you remove the following lines there is no OOM :
    tray.add(trayIcon);
    tray.remove(trayIcon);
    so it seems to me that TrayIcon is the origin of the OOM
    - the weak reference is there in order to see when a trayIcon can be garbage collected
    Edited by: lemmel on May 5, 2009 7:22 AM - added comments

    So I did the test and:
    - you were right about the vector, but this one was added only for debugging purpose (find the OOM cause)
    - your code sample get a OOM with my computer as well as mine (with the vector removed obviously); I made some alteration to your code see below
    could you try changing your java memory settings (see below) ?
    P.S. :
    - I first tried with your code as it was, got the OOM, then decided to give some time to the garbage collector (and later to force a call to it) by adding the lines with the tag ADDED
      import java.awt.*;
      import java.awt.image.BufferedImage;
      static class MyPopup extends PopupMenu {
      public static void main(String[] args) throws Exception{
        SystemTray tray = SystemTray.getSystemTray();
        BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
        int i = 0;                       //ADDED
        while (true) {
            PopupMenu popup = new MyPopup();
            TrayIcon newTrayIcon = new TrayIcon(image, "Frame Title", popup);
            tray.add(newTrayIcon);
            tray.remove(newTrayIcon);
            if((i%10)==0) {              //ADDED
              System.gc();               //ADDED
              System.runFinalization();  //ADDED
              Thread.sleep(100);         //ADDED
            }                            //ADDED
            i ++;                        //ADDED
        }I removed the array trick in the MyPopup class in order to be able to do at least one loop (see my settings below)
    - my environnement :
    ---- debian testing, kernel 2.6.26-1-686, libc6 2.9-4
    ---- tried with both java 6.12 and 6.13 (1.6.0_13; Java HotSpot(TM) Client VM 11.3-b02), use Netbeans NetBeans IDE 6.5 (Build 200811100001)
    ---- put those flags: -Xms5m -Xmx5m

  • I have a memory leak, objective-c 2.0, and garbage collector...

    the code i am using is a modification of the code/problem found in "Cocoa with Objective-C", chapter 3.
    i have tried to use the objective-c 2.0 garbage collector methodology, using @property, @synthesize, etc. when i run the code as listed below i get a leaking message.
    [Session started at 2008-02-01 23:33:37 -0500.]
    2008-02-01 23:33:38.070 SongsFoundationTool[28876:10b] * _NSAutoreleaseNoPool(): Object 0x2040 of class NSCFString autoreleased with no pool in place - just leaking
    Stack: (0x96b10178 0x96a3e0f8)
    2008-02-01 23:33:38.075 SongsFoundationTool[28876:10b] Song 1: We Have Exposive
    2008-02-01 23:33:38.076 SongsFoundationTool[28876:10b] * _NSAutoreleaseNoPool(): Object 0x2060 of class NSCFString autoreleased with no pool in place - just leaking
    Stack: (0x96b10178 0x96a3e0f8)
    2008-02-01 23:33:38.078 SongsFoundationTool[28876:10b] Song 2: Loops of Fury
    The Debugger has exited with status 0.
    when i include the commented out section, in the implementation file section, the description method, and use song1 and song2, in main, instead of song1.name and song2.name the program seems to run fine.
    The Debugger has exited with status 0.
    [Session started at 2008-02-01 23:38:24 -0500.]
    2008-02-01 23:38:24.375 SongsFoundationTool[28936:10b] Song 1: We Have Exposive
    2008-02-01 23:38:24.379 SongsFoundationTool[28936:10b] Song 2: Loops of Fury
    The Debugger has exited with status 0.
    please help me understand what's happening here.
    also, why was it necessary to use
    @property(copy, readwrite) NSString *name;
    @property(copy, readwrite) NSString *artist;
    instead of
    @property(readwrite) NSString *name;
    @property(readwrite) NSString *artist;
    thanks everyone, the code is below.
    // ....................... header file ...............
    #import <Cocoa/Cocoa.h>
    @interface Song : NSObject {
    NSString *name;
    NSString *artist;
    @property(copy, readwrite) NSString *name;
    @property(copy, readwrite) NSString *artist;
    @end
    //.................... the implementation file ..................
    #import "Song.h"
    @implementation Song
    @synthesize name;
    @synthesize artist;
    -(NSString *) description
    return [ self name ];
    @end
    //................................ main............................
    #import <Foundation/Foundation.h>
    #import "Song.h"
    int main (int argc, const char * argv[]) {
    Song *song1 = [ [ Song alloc ] init ];
    song1.name= @"We Have Exposive" ;
    [ song1 setArtist: @"The Future Sound Of Londown" ];
    Song *song2 = [ [ Song alloc ] init ];
    [ song2 setName: @"Loops of Fury" ];
    [ song2 setArtist: @"The Chemical Brothers" ];
    // Display Object
    NSLog( @"Song 1: %@", song1.name );
    NSLog( @"Song 2: %@", song2.name );
    // include statements below if -description method is uncommented
    // then comment out the two statements above. no memory leak if the code
    // is used from the statements below and - description is not commented out and
    // the two NSLog statements above are commented out.
    NSLog( @"Song 1: %@", song1 );
    NSLog( @"Song 2: %@", song2 );
    return 0;
    }

    Normally, your main only has a call to NSApplicationMain(). If you aren't doing a traditional MacOS X application, you will still want at least NSApplicationLoad() to get enough of the runtime to avoid those messages.
    I don't know for sure about the syntax of Objective-C 2.0. That stuff is all new. What error message are you getting that indicated that (copy, readwrite) is required? Could you provide a link to the actual example source? I did a quick check and assign and readwrite are the defaults. It is possible that readwrite by itself makes no sense. But I'm just guessing.

  • Memory leak when I use function with bstr_t type

    Hello,
    I use Visual C++ 6 and TestStand 3.1.
    I use the tool: Purify from Rational Instruments to detect memory leak in my code.
    When I use in my code, functions from the TestStand API using bstr_t types: GetValString, GetType... memory leaks appear.
    Do you have an idea to solve this problem?
    Thanks

    Breizh,
    Etes vous sur que le problèmes soit lié au type bstr_r ?
    Pouvez vous me faire parvenir un exemple de code mettant en oeuvre la fuite mémoire?
    Raphaël T.
    NI FRANCE
    Cordialement,
    Raphael T

  • COM+ and OLEDB - memory leak in OCI dlls

    Hi forum,
    I've a COM+ DLL written in C++ which uses OLEDB(Oracle 8.1.7 provider) to reach to the 8i database. I've observed that after some 1000 database activities the DLLhost.exe hogs on memory to the tune of 50MB and never releases the same. I also saw the same behavior with a Win32 console application. For some reason the Uninitialize of the IDBIntialize does not seem to reduce the memory. I also ran bounce checker on my code. And its pointing to the OCI dlls for a memory leak of 18K per each database activity.
    I downloaded the OLEDB sample code(VCOLEMRecordsSample) from the OTN site:-
    http://otn.oracle.com/sample_code/tech/windows/ole_db/oledb8/index.html
    This also seems to hold on to memory after successive run of SQL queries.
    Is there anything that I am missing. I am curious about the fact that it happens with the sample app hosted on the OTN site. Do I need some OCI patches to be applied to the client? In fact, applied couple of them, but does not help.
    Appreciate any pointers!

    I am using 8.1.7.3.2. In fact I applied this patch recently.
    Also today I detected a memory leak in my code.
    After GetColumnsInfo() call I was not releasing the last param(ppStringsBuffer).
    This seems to have fixed the problem. I tried running the win32 console app for 5,000 runs(each run has 2 SQL queries and 1 stored proc). The peak mem usage stays stable around 26MB and the mem usage varies from 8MB to 26MB. I guess this is fine, any info?

  • Memory leak w/ NSArray

    Can anyone find the memory leak in this code? The code is a simplification of code from documentation of 'NSSearchPathForDirectoriesInDomains'.
    - (BOOL)makeLeak
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([paths count] > 0) {
    return YES;
    return NO;
    }

    Got it. It's not leaking. I was calling it from within secondary thread and hadn't wrapped that section of code with NSAutoreleasePool.

  • How to root out memory leak with  Java JNI & Native BDB 11g ?

    We are testing a web application using the 32-bit compiled native 11g version of BDB (with replication) under 32-bit IBM 1.5 JVM via JNI under 64-bit RedHat Linux. We are experiencing what appears to be a memory leak without a commensurate increase in Java heap size. Basically the process size continues to grow until the max 32-process size is reached (4Gb) and eventually stops running (no core). Java heap is set to 2Gb min/max. GCs are nominal, so the leak appears to be native and outside Java bytecode.
    We need to determine whether there is a memory leak in BDB, or the IBM JVM or simply a mis-use of BDB in the Java code. What tools/instrumentation/db statistic should be used to help get to root cause? Do you recommend using System Tap (with some particular text command script)? What DB stats should we capture to get to the bottom of this memory leak? What troubleshooting steps can you recommend?
    Thanks ahead of time.
    JE.
    Edited by: 787930 on Aug 12, 2010 5:42 PM

    That's troublesome... DB itself doesn't have stats that track VM in any useful way. I am not familiar with SystemTap but a quick look at it seems to imply that it's better for kernel monitoring than user space. It's pretty hard to get DB to leak significant amounts of memory. The reason is that it mostly uses shared memory carved from the environment. Also if you are neglecting to close or delete some object DB generally complains about it somewhere.
    I don't see how pmap would help if it's a heap leak but maybe I'm missing something.
    One way to rule DB out is to replace its internal memory allocation functions with your own that are instrumented to track how much VM has been allocated (and freed). This is very easy to do using the interfaces:
    db_env_set_func_malloc()
    db_env_set_func_free()
    These are global to your process and your functions will be used where DB would otherwise call malloc() and free(). How you get usage information out of the system is an exercise left to the reader :-) If it turns out DB is the culprit then there is more thinking to do to isolate the problem.
    Other ideas that can provide information if not actual smoking guns:
    -- accelerate reproduction of the problem by allocating nearly all of the VM to the JVM and the DB cache (or otherwise limit the allowable VM in your process)
    -- change the VM allocated to the JVM in various ways
    Regards,
    George

  • Memory leak problem while passing Object to stored procedure from C++ code

    Hi,
    I am facing memory leak problem while passing object to oracle stored procedure from C++ code.Here I am writing brief description of the code :
    1) created objects in oracle with the help of "create or replace type as objects"
    2) generated C++ classes corresponding to oracle objects with the help of OTT utility.
    3) Instantiating classes in C++ code and assigning values.
    4) calling oracle stored procedure and setting object in statement with the help of setObject function.
    5) deleted objects.
    this is all I am doing ,and getting memory leak , if you need the sample code then please write your e-mail id , so that I can attach files in reply.
    TIA
    Jagendra

    just to correct my previous reply , adding delete statement
    Hi,
    I am using oracle 10.2.0.1 and compiling the code with Sun Studio 11, following is the brief dicription of my code :
    1) create oracle object :
    create or replace type TEST_OBJECT as object
    ( field1 number(10),
    field2 number(10),
    field3 number(10) )
    2) create table :
    create table TEST_TABLE (
    f1 number(10),f2 number (10),f3 number (10))
    3) create procedure :
    CREATE OR REPLACE PROCEDURE testProc
    data IN test_object)
    IS
    BEGIN
    insert into TEST_TABLE( f1,f2,f3) values ( data.field1,data.field2,data.field3);
    commit;
    end;
    4) generate C++ classes along with map file for database object TEST_OBJECT by using Oracle OTT Utility
    5) C++ code :
    // include OTT generate files here and other required header files
    int main()
    int x = 0;
    int y = 0;
    int z =0;
    Environment *env = Environment::createEnvironment(Environment::DEFAULT);
    Connection* const pConn =
    env->createConnection"stmprf","stmprf","spwtrgt3nms");
    const string sqlStmt("BEGIN testProc(:1) END;");
    Statement * pStmt = pConn->createStatement(sqlStmt);
    while(1)
    TEST_OBJECT* pObj = new TEST_OBJECT();
    pObj->field1 = x++;
    pObj->field2 = y++;
    pObj->field3 = z++;
    pStmt->setObject(1,pObj);
    pStmt->executeUpdate();
    pConn->commit();
    delete pObj;
    }

  • Memory leak with large files and this code?

    Okay, so the following code will not complete. 
    Basically what I am doing is opening 5 files and generating a PDF document from the already opened Report file, which is renewed prior to the PDF export operation.  I left out the general stuff at the start.  I am also writing out the location of the PDF to a HTML file, which acts as an index of the exported PDF documents.
    I believe it is due to some sort of memory leak issue, but it could be something else or just my code.  I have not stepped through this code, but for small file sizes of say less than 40 megs per file, it works fine.  For file sizes along these lines:
    File 1 = 230 megs
    File 2,3 = 26 megs
    File 4,5 = 8 megs
    it will belch erors at the end of about the 5th iteration through the For loop.  It will complete the 5th iteration however.  Here are the errors generated:
    84   10/26/2006 9:35:15 AM Error:
    85   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p1.TDM" file is invalid.
         (Error no. 6)
    86   10/26/2006 9:40:19 AM Error:
    87   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p2.TDM" file is invalid.
         (Error no. 6)
    88   10/26/2006 9:45:17 AM Error:
    89   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p3.TDM" file is invalid.
         (Error no. 6)
    90   10/26/2006 9:53:07 AM Error:
    91   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p8.TDM" file is invalid.
         (Error no. 6)
    92   10/26/2006 10:00:39 AM Error:
    93   File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p9.TDM" file is invalid.
         (Error no. 6)
    94   10/26/2006 10:01:01 AM Error:Error occured during file creation.
    95   10/26/2006 10:01:01 AM Error:
         Error in <GM315 Pa...sing.VBS> (Line: 185, Column: 5):
         File handle for "W:\TR-2051-2100\TR-2060 - BAS Arctic PTC\Vnom\00-99\VnomCombined00-99\p1.TDM" file is invalid.
         (Error no. 6)
    For files of a larger size, like:
    File 1 = 7500 megs
    File 2,3 = 80 megs
    File 4,5 = 25 megs
    This occurs after about 2-3 iterations through the loop.
    see attachment for code.
    Attachments:
    ForLoopCode.txt ‏11 KB

    i am having a similar error randomly inserted in the log 
    25   10/1/2009 1:58:36 PM Error:
    26   File handle for "C:\Program Files\Summitek\Spartan\data\tdm\S Parameter Test $SSN$ 49.TDMS" file is invalid.
         (Error no. 6)
    and
    31   10/1/2009 1:58:37 PM Error:
    32   File handle for "C:\Program Files\Summitek\Spartan\www\temp\Test_$SSN$ 49_602313172.pdf" file is invalid.
         (Error no. 6)
    it doesn't seem to be causing an immediate problem, but i have had several unexplained Diadem lockups.
    they occur in log after i use CALL DATAFILELOADSEL and CALL PICpdfexport
    help? what does this mean
    jim

Maybe you are looking for