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.

Similar Messages

  • Fixing Memory Leaks in AIR App?

    Hi Friends,
    I'm been facing this memory leaks issue in our app and this has taken enough of our time and resources and we are not being able to find a solution for it.
    I have identified the problem in the module where we primarily need memory related fixes which is - We are setting Repeater's recycleChildren() property to true/false based upon certain conditions which we cant change. Now when this property is set to false Repeater is supposed to be removing its last created objects from memory and creating fresh ones. In our case repeater is unable to delete those. When I managed to get their instances (using createdChildren()) and freed them in code I called System.gc() for releasing the memory back to OS. Now what is happening is that this approach works fine when I run the app from code but when I create its installer (from Installsheild) and formally out in on machines it does not work. I came to know the reason from following blogs:
    http://jvalentino.blogspot.com/2009/05/flex-memory-issue-3-garbage-collection.html
    http://gskinner.com/blog/archives/2006/06/as3_resource_ma.html
    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/System.htm l#gc()
    http://stackoverflow.com/questions/192373/force-garbage-collection-in-as3
    http://gskinner.com/blog/archives/2006/08/as3_resource_ma_2.html
    Guys, can anyone of you suggest what should I do here? This has become a delivery bottleneck and we need to give a fix where the memroy is released periodically and efficiently so that the end user's system does not hang.
    Please help.
    Shubhra

    Are you sure it doesn't ? Maybe flash does release memory but the OS leaves it assigned as described in the below comment from http://www.mikechambers.com/blog/2008/08/06/what-are-your-biggest-issues-with-adobe-air/co mment-page-3/#comment-26330
    "I just finished doing more experiments, I looks like the AIR app  does free the memory, but the OS leaves it assignned to the app process,  until other apps requiere that memory. So, looks like it is a natural  behaviour and the memory leak is not as terrible as I thougth."

  • Memory Leak Issue for Adobe Access iOS API

    Hi,
    We are trying to develop an iOS app (with ARC enabled) using Adobe Acces API 4.0 and we have identified that the function [drmManager createDRMSession] has memory leak.
    DRMSESSION = [drmManager createDRMSession:METADATA playlist:PLAYLIST error:nil complete:^() {}];
    We are using:
    DRMSESSION  -> weak
    METADATA    ->strong  (as need to share within object)
    PLAYLIST       ->strong  (as need to share within object)
    After calling this function, the object is unable to dealloc and most of the leaking object related to networking (such as CFNetwork...)
    Is this a known issue for the Adobe Access iOS API or we are missing some key steps.
    Any suggestions is appreciated. Thanks in advance.

    ans0600, sorry about that, I read Hiroshi's forward too quickly.  I've done a little digging and have come up with two work-arounds:
    Create a file with ARC disabled to translate the returned object to be an autorelease
    declare the returned DRMSession as __unsafe_unretained and use CFRelease, as noted on stackexchange
    In the future we may change this method to return an autoreleased object to avoid this issue.  Let us know if you have any further questions!

  • 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.

  • 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 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();
    }

  • Memory Leak Problem at Adobe LiveCycle Server 9.0

    Hi All,
    We want to upgrade our system to 9.0. During the performance test we have found memory Leak problem at ALS 9.0. I explain the detailed problematic issue below. Is there any body who has any suggest?
    We have Adobe Livecycle ES2 9.0 SP2 installed on WAS 6.1. But also WAS on Windows Server 2008 R2. We call java web services from .Net Web service for generating PDFs.
    On Java side “com/adobe/internal/pdftoolkit/services/javascript/GibsonMemoryTracking” class is causing Memory Leak problem at server.
    Our .Net Codes. I copied below. First we generate PDF then we convert this pdf to static pdf.
    First We call the GeneratePDF function.
    public static bool GeneratePdf(Document document, byte[] pdfTemplate)
            try
                //Create a FormDataIntegrationService object and set authentication values
                FormDataIntegrationService formDataIntegrationClient = new FormDataIntegrationService();
                formDataIntegrationClient.Credentials = new System.Net.NetworkCredential(Settings.ALCUserName, Settings.ALCPassword);
                //Import XDP XML data into an XFA PDF document
                ALCFormDataIntegrationService.BLOB inXMLData = new ALCFormDataIntegrationService.BLOB();
                //Populate the BLOB object
                inXMLData.binaryData = System.Text.Encoding.UTF8.GetBytes(document.XmlData);
                //Create a BLOB that represents the input PDF form
                ALCFormDataIntegrationService.BLOB inPDFForm = new ALCFormDataIntegrationService.BLOB();
                inPDFForm.binaryData = pdfTemplate;
                //Import data into the PDF form
                ALCFormDataIntegrationService.BLOB results = formDataIntegrationClient.importData(inPDFForm, inXMLData);
                document.PdfData = results.binaryData;
                Utility.Log("GeneratePdf", "Pdf generated successfully.", LogLevel.Info);
                return true;
            catch (Exception ex)
                document.ReturnCode = "22";
                document.ReturnMsg = "Exception on generating the pdf";
                Utility.Log("GeneratePdf", "Exception: " + ex.Message, LogLevel.Error);
                return false;
    Then We call the ConvertPDF function.
    public static bool ConvertPdf(Document document)
            try
                //Create a OutputServiceService object
                OutputServiceService outputClient = new OutputServiceService();
                outputClient.Credentials = new System.Net.NetworkCredential(Settings.ALCUserName, Settings.ALCPassword);
                //Create a BLOB object
                ALCOutputService.BLOB inData = new ALCOutputService.BLOB();
                //Populate the BLOB object
                inData.binaryData = document.PdfData;
                //Set rendering run-time options
                RenderOptionsSpec renderOptions = new RenderOptionsSpec();
                renderOptions.cacheEnabled = true;
                //Create a non-interactive PDF document
                ALCOutputService.BLOB results = outputClient.transformPDF(inData, TransformationFormat.PDF, PDFARevisionNumber.Revision_1, false, null, PDFAConformance.B, false);
                document.PdfData = results.binaryData;         
                Utility.Log("ConvertPdf", "Pdf converted successfully.", LogLevel.Info);
                return true;
            catch (Exception ex)
                document.ReturnCode = "22";
                document.ReturnMsg = "Exception on converting dynamic pdf to static pdf";
                Utility.Log("ConvertPdf", "Exception: " + ex.Message, LogLevel.Error);
                return false;
    Our System Configuration:
    Expiry date: Never Version: 9.0.0.0,
    GM Patch Version: SP2
    Service Pack Version: unknown
    ADOBE® LIVECYCLE® PDF Generator ES2
    9.0.0.0
    SP2
    ADOBE® LIVECYCLE® Reader Extensions ES2
    9.0.0.0
    SP2
    ADOBE® LIVECYCLE® Output ES2
    9.0.0.0
    SP2
    We changed some configuration which is suggested by Adobe. But this change does not solve our problem.
    Changed Configurations via ADMINUI
    Memory Leak Problem which is viewed via wily tool:

    Hi Mahir,
    Can you attach the results of this performance test where we can see how GibsonMemoryTracking class is causing the memory leak issue.
    Also do you see any stackTrace in the LiveCycle server logs related to memory / heap when you run this performance test ?
    Thanks,
    Simer

  • 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

  • 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 - Oracle 9.2 ADO/OLE DB Select Distinct

    I'm using ADO (MDAC 2.8) and Oracle OLE DB (9.2.0.1.0) to access an Oracle 9.2.0.1.0 database. All queries run fine, but when I issue a query with the distinct keyword (e.g. Select distinct...), the application leaks memory. The memory leak does not occur when issuing the same query to MS SQL Server 2000. I also installed the latest 9.2.0.2.0 Oracle OLE DB update, but it didn't fix the problem.
    The same problem appears to have been fixed with Oracle ODBC drivers. "Fixed memory leak when using �select distinct�. (Bug2685365)"
    http://otn.oracle.com/software/tech/windows/odbc/htdocs/whatsnew.htm
    I've also seen the same problem reported on DBForums.com.
    "...select distinct query made through ADO causes a memory leak in that object... This issue is known by Oracle and I think that there may be a patch available for Oracle 9."
    http://dbforums.com/arch/210/2003/3/733498
    This is a critical problem for the product we are developing.
    Is there a fix available for this problem?
    Bob

    Thanks, I looked for the update yesterday, but all Oracle had posted was the update for 9.2.0.2.0.
    Luckily, as of this morning there is a new update available from Oracle, 9.2.0.4.0. I installed it and it fixed the memory leak with OLE DB and Select Distinct queries.
    The installer for 9.2.0.4.0 is a bit rough. It doesn't stop the Distributed Transaction Coordinator or Oracle MT Service on your computer, so you must stop them before installing. Also, you can't install all the products at once and must install the Oracle uninstaller first.

  • Memory leak in string class

    We have developed our application in Solaris 10 environment. While running Purify on that it shows leak in the string class. This leak is incremental and so process size keeps in increasing. If we replace string with char array, the leaks disappears and process size also becomes stable.
    Following is the snapshot of the memory leak stack reported by Purify:
    MLK: 4505 bytes leaked in 85 blocks
    * This memory was allocated from:
    malloc [rtlib.o]
    operator new(unsigned) [libCrun.so.1]
    void*operator new(unsigned) [rtlib.o]
    __rwstd::__string_ref<char,std::char_traits<char>,std::allocator<char> >*std::basic_string<char,std::char_traits<char>,std::allocator<char> >::__getRep(unsigned,unsigned) [libCstd.so.1]
    char*std::basic_string<char,std::char_traits<char>,std::allocator<char> >::replace(unsigned,unsigned,const char*,unsigned,unsigned,unsigned) [libCstd.so.1]
    std::basic_string<char,std::char_traits<char>,std::allocator<char> >&std::basic_string<char,std::char_traits<char>,std::allocator<char> >::operator=(const char*) [libCstd.so.1]
    Has anyone faced this problem earlier or is there any patch available for this?

    Over time, we have found and fixed memory leaks in the C++ runtime libraries.
    Get the latest patches for the compiler you are using. (You didn't say which one.) You can find all patches here:
    [http://developers.sun.com/sunstudio/downloads/patches/index.jsp]
    Also get the latest Solaris patch for the C++ runtime libraries, listed on the same web page.
    If that doesn't fix the problem, please file a bug report at
    [http://bugs.sun.com]
    with a test case that can be compiled and run to demonstrate the problem.

  • 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

  • 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.

Maybe you are looking for

  • I can't save documents in Pages.

    I can't save documents in Pages. I get a "file does not exist" error message. I've tried changing the file name, length, and location. To no avail. This is only sporadic.

  • Error in setting CTX_DLL prpperties

    when i try to set those properties, errors occurs: Begin      CTX_DDL.CREATE_PERFERENCE('ENG_LEXER', 'BASIC_LEXER');      CTX_DLL.SET_ATTRIBUTE('ENG_LEXER', 'INDEX_THEMES','YES');      CTX_DLL.SET_ATTRIBUTE('ENG_LEXER', 'THEME_LANGUAGE','ENGLISH'); E

  • Regarding Purchase Order Smartform

    hi all,      Can you send the logic for Calculating Taxes(Local Tax and Central Tax) for Purchase Order . Regards Rami Reddy

  • Buying new games for the ipod Nano 5G

    When I looked at the requirement for the games in the iTunes store the overall description said that these games (clickwheel) can be played on the 5th Gen. Nano, but when I look at the requirements for each individual game it says that the games are

  • IMac G5  shuts down unexpectedly

    Hi friends at Apple Discussions, This week my iMac has shut down by itself unexpectedly about once a day. Immediately after it shuts down it will not start up, although after a 10 minute wait or so, it will start up and run just fine. Nothing had bee