Memory leak in String(byte[] bytes, int offset, int length)

Has anyone run into memory leak problem using this String(byte[] bytes, int offset, int length) class? I am using it to convert byte array to string, and I am showing memory leak using this class. Any idea what is going on?

Hi,
If you post in Native methods forum I assume you are using this constructor in the native side.
Be aware that getting char * from jstring eats memory that you must free before returning from native with env->ReleaseStringUTFChars().
--Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Similar Messages

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

  • Memory leak using 10.2.0.3 OCI client on Solaris

    Hi,
    We are using OCI client libraries to connect our C++ program to the Oracle Database. The program does a lot of selects, inserts and SP calls.
    Oracle client and Oracle server both are 10.2.0.3.
    We have been observing a memory leak of 4M bytes in the C++ program every few minutes since last few days. On debugging through Purify, libumem, and Sun Studio 12, we finally managed to narrow down the problem to the Oracle client library OCI calls.
    The Sun Studio leak check shows the following -
    Leak #37, Instances = 157, Bytes Leaked = 655004
    kpummapg + 0x00000098
    kghgex + 0x00000648
    kghfnd + 0x000005BC
    kghalo + 0x00000A6C
    kghgex + 0x000003BC
    kghfnd + 0x000005BC
    kghalo + 0x00000A6C
    kghgex + 0x000003BC
    kghfnd + 0x000005BC
    kghalo + 0x00000A6C
    kpuhhalo + 0x00000558
    kpugdesc + 0x00000AD4
    kpugparm + 0x00000374
    COCIResultSet::InterpretData() + 0x000001B4
    COCIResultSet::COCIResultSet(COCIStatement*,OCIStmt*,OCIError*) + 0x000000A4
    COCIStatement::PrepareResult() + 0x00000190
    A select is executed, a resultset is fetched and the resultset is immeidately closed. The same piece of code has been running at various production systems without any problems. Most of the other sites are either 10.2.0.4 or 9i.
    On searching Metalink and various other forums, I found similar issues faced in 10.2.0.1.
    Could someone advise if there are any bugs corresponding to this which have been closed. Would upgrading to 10.2.0.4 solve the problem?
    Thanks.

    Hi,
    Apparently a similar issue is being discussed over here:
    Re: Memory Leak
    Hope it helps.
    Regards,
    Naveed.

  • Memory leak using 10.2.0.3 OCCI client on Solaris 10

    Hi,
    We are using OCCI client libraries to connect our C++ program to the Oracle Database. The program does a lot of selects, inserts and SP calls.
    Oracle client and Oracle server both are 10.2.0.3 on Solaris 10.
    We have been observing a memory leak of 4M bytes in the C++ program every few minutes since last few days. On debugging through Purify, libumem, and Sun Studio 12, we finally managed to narrow down the problem to the Oracle client library OCI calls.
    The Sun Studio leak check shows the following -
    Leak #37, Instances = 157, Bytes Leaked = 655004
    kpummapg + 0x00000098
    kghgex + 0x00000648
    kghfnd + 0x000005BC
    kghalo + 0x00000A6C
    kghgex + 0x000003BC
    kghfnd + 0x000005BC
    kghalo + 0x00000A6C
    kghgex + 0x000003BC
    kghfnd + 0x000005BC
    kghalo + 0x00000A6C
    kpuhhalo + 0x00000558
    kpugdesc + 0x00000AD4
    kpugparm + 0x00000374
    COCIResultSet::InterpretData() + 0x000001B4
    COCIResultSet::COCIResultSet(COCIStatement*,OCIStmt*,OCIError*) + 0x000000A4
    COCIStatement::PrepareResult() + 0x00000190
    A select is executed, a resultset is fetched and the resultset is immeidately closed. The same piece of code has been running at various production systems without any problems. Most of the other sites are either 10.2.0.4 or 9i.
    On searching Metalink and various other forums, I found similar issues faced in 10.2.0.1.
    Could someone advise if there are any bugs corresponding to this which have been closed. Would upgrading to 10.2.0.4 solve the problem?
    Thanks.

    Please ... one post and one post only in the group most appropriate to your inquiry. Please open an SR at metalink.

  • Memory leak issue in iPhone app

    We developed a little program to display PDF's on the iPhone, but it's crashing after scrolling through xx number of pages with low memory error. The app runs fine in the simulator but crashes on the original iphone. I ran the memory leak debugger tool from xcode and got the following:
    http://picasaweb.google.com/momopi/MiscCollection#5384555524546579922
    (click on magnify glass tool to zoom in)
    Weird part is when I run the same on iphone simulator I only get 2 small memory leak warnings (128 bytes each), but on the iphone I get a lot more warnings and it crashes.
    Has anyone seen anything like this?

    Perhaps you don't have any meaningful leaks. Your program could simply consume too much memory. It has been many years since keeping a small memory footprint was important. Now that Apple has thrown embedded programming to the masses, everyone has forgotten about that.

  • Memory leaks in NI-DAQ 6.9.1

    Can anyone tell me if the API for NI-DAQ 6.9.1 has been purified to eliminate all memory leaks? I'm using DIG_Block_In() etc. with PCI-653X DIO cards. My Win2K MSC++ V6 Purify (tm) reports many potential leaks similar to the following:
    [I] MPK: Potential memory leak of 11550 bytes from 350 blocks allocated in RegistrySession::~RegistrySession(void)
    Distribution of potentially leaked blocks
    11550 bytes from 350 blocks of 33 bytes (first block: 0x04a34ae8)
    Allocation location
    malloc [msvcrt.DLL]
    RegistrySession::~RegistrySession(void) [nipsm.dll]
    moot::moot(basic_string,allocator> const&) [nipsm.dll]
    moot::moot(basic
    _string,allocator> const&) [nipsm.dll]
    moot::load(PSMQueue&) [nipsm.dll]
    BinaryFileProxy::Load(PSMQueue&) [nipsm.dll]
    BinaryFileProxy::Begin(void) [nipsm.dll]
    KeyProxy:pen(moot const&,DWORD) [nipsm.dll]
    CfqCloseConnectionToServer [nicfq32.dll]
    CfqQueryDigitalAvailability [nicfq32.dll]
    moot::moot(basic_string,allocator> const&) [nipsm.dll]

    John,
    Thanks for your reply. I'll include another Purify "Potential Leak" report and try to annotate it more.
    This is the biggest reported leak at 11550 bytes from the destructor of an object called RegistrySession found in nipsm.dll.
    The lines below "RegistrySession::~RegistrySession(void) [nipsm.dll]" form a call stack reading down. ie object moot called RegistrySession, and BinaryFileProxy::Load() called that, etc. The RegistrySession destructor is really the only culprit for allocating memory then losing it. The whole chain of events starts, however, at a call to CfqQueryDigitalAvailability in the nicfq32.dll.
    Now, my application certainly didn't call this and I have no idea what it's trying to do, but I suspect that it's called sometime
    during the loading and initialization of nidaq32.dll which I link against.
    If you indeed Purify your libraries prior to release then you should be able to duplicate my results.
    I can send you my code if you like.
    Thanks for you help,
    Dan Stine
    MPK: Potential memory leak of 11550 bytes from 350 blocks allocated in RegistrySession::~RegistrySession(void)
    Distribution of potentially leaked blocks
    Allocation location
    malloc [msvcrt.dll]
    RegistrySession::~RegistrySession(void) [nipsm.dll]
    moot::moot(basic_string,allocator> const&) [nipsm.dll]
    moot::moot(basic_string,allocator> const&) [nipsm.dll]
    moot::load(PSMQueue&) [nipsm.dll]
    BinaryFileProxy::Load(PSMQueue&) [nipsm.dll]
    BinaryFileProxy::Begin(void) [nipsm.dll]
    KeyProxy:pen(moot const&,DWORD) [nipsm.dll]
    CfqCloseConnection
    ToServer [nicfq32.dll]
    CfqQueryDigitalAvailability [nicfq32.dll]

  • SocketInputStream.read(byte[], int, int) extremely slow

    Hi everyone,
    I'm trying to send several commands to a server and for each command read one or more lines as response. To do that I'm using a good old Socket connection. I'm reading the response lines with BufferedReader.readLine, but it's very slow. VisualVM says, that SocketInputStream.read(byte[], int, int) is consuming most of the cpu time. A perl script, which does the same job, finishes in no time. So it's not a problem with the server.
    I'm runnning java version "1.6.0_12"
    Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
    Java HotSpot(TM) Server VM (build 11.2-b01, mixed mode) on Linux henni 2.6.25-gentoo-r7 #3 SMP PREEMPT Sat Jul 26 19:35:54 CEST 2008 i686 Intel(R) Core(TM)2 Duo CPU E6550 @ 2.33GHz GenuineIntel GNU/Linux and here's my code
    private List<Response> readResponse() throws IOException {
            List<Response> responses = new ArrayList<Response>();
            String line = "";
            while ( (line = in.readLine()) != null) {
                int code = -1;
                try {
                    code = Integer.parseInt(line.substring(0, 3));
                    line = line.substring(4);
                } catch (Exception e) {
                    code = -1;
                // TODO create different response objects ?!?
                NotImplemented res = new NotImplemented(code, line);
                responses.add(res);
                // we received an "end of response" line and can stop reading from the socket
                if(code >= 200 && code < 300) {
                    break;
            return responses;
        }Any hints are appreciated.
    Best regards,
    Henrik

    Though it's almost an sscce I posted there, I will try to shrink it a little bit:
    Dummy server:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class Server {
        public Server() throws IOException {
            ServerSocket ss = new ServerSocket(2011);
            Socket sock = ss.accept();
            BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            PrintStream ps = new PrintStream(sock.getOutputStream());
            ps.println("200 Welcome on the dummy server");
            String line = "";
            while(line != null) {
                line = br.readLine();
                ps.println("200 Ready.");
        public static void main(String[] args) throws IOException {
            new Server();
    }the client:
    import java.io.IOException;
    import java.io.PrintStream;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.util.Scanner;
    import de.berlios.vch.Config;
    public class Client {
        private Socket socket;
        private PrintStream out;
        private Scanner scanner;
        public Client(String host, int port, int timeout, String encoding)
            throws UnknownHostException, IOException {
            socket = new Socket();
            InetSocketAddress sa = new InetSocketAddress(host, port);
            socket.connect(sa, timeout);
            out = new PrintStream(socket.getOutputStream(), true, encoding);
            scanner = new Scanner(socket.getInputStream(), encoding);
        public synchronized void send(String cmd) throws IOException {
            // send command to server
            out.println(cmd);
            // read response lines
            readResponse();
        public void readResponse() throws IOException {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
                int code = -1;
                try {
                    code = Integer.parseInt(line.substring(0, 3));
                    line = line.substring(4);
                } catch (Exception e) {
                    code = -1;
                if (code >= 200 && code < 300) {
                    break;
        public static void main(String[] args) {
            try {
                Client con = new Client("localhost", 2011, 500, "utf-8");
                con.readResponse();
                con.send("version 0.1");
                con.send("menu = new menu Feeds");
                con.send("menu.EnableEvent close");
                con.send("menu.SetColorKeyText -red 'Öffnen'");
                for (int i = 0; i < 100; i++) {
                    String groupId = "group"+i;
                    long start = System.currentTimeMillis();
                    con.send(groupId+" = menu.AddNew OsdItem '"+groupId+"'");
                    con.send(groupId+".EnableEvent keyOk keyRed");
                    long stop = System.currentTimeMillis();
                    System.out.println((stop-start)+"ms");
            } catch (Exception e) {
                e.printStackTrace();
    }This code makes me believe, it's not a java problem, but some system setting of my os.

  • Hex code string -- byte array

    hi everyone,
    i have a bunch of hexadecimal code which is read from a text file into a String.
    i want to put this String into a byte array without changing anything.
    my algorithm is like this -
    String strFromTextFile = "FFD8FFE0001";
    * put strFromTextFile into byteArr[ ]
    byteArr[0] == 'F';
    byteArr[1] == 'F';
    byteArr[2] == 'D';

    hi, i think this simple code will fulfill ur need
    public class hex {
         public static void main(String[] args) {
              String str= "AFFD8FFE0001";
              byte hexbytes[] =     hexstore(str);
    public     static byte[] hexstore(String str)
          int length = str.length();
          if((length%2)!=0)
               length++;
               str = new String(str+"0");
          byte[] a = new byte[length/2];
          for(int i=0,j=0;i<str.length();i=i+2,j++)
              byte c =(byte) str.charAt(i);     
              if(c<65)
                   c= (byte)((int)c-48);               
              else
                   c= (byte)(10+(int)c-65);
                   c=(byte)((int)c<<4);
              byte d =(byte) str.charAt(i+1);
              if(d<65)
                   d= (byte)((int)d-48);               
              else
                   d= (byte)(10+(int)d-65);
                   c = (byte)(c | d);
                   a[j]=c;
              for(int i=0;i<length/2;i++)
                   System.out.println("byte "+((int)a));
              return a;
    example ( for first 2 characters)
    AF has to be stored as 1010 1111
    1010 1111 is stoted in a[0];

  • System.InsufficientMemoryException: Failed to allocate a managed memory buffer of 268435456 bytes. The amount of available memory may be low. --- System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.

    Appfabric 1.1 server setup on 3 Windows server 2008 R2 machines.
    Client windows 7 64 bit.
    Because there is no bulkupdate ,we are trying to persist around 4000 objects wrapped in a CLR object.
     [Serializable]
        public class CacheableCollection<T> : ICacheable, IEnumerable<T>
            where T : class, ICacheable
            [DataMember]
            private Dictionary<string, T> _items;
            public IEnumerator<T> GetEnumerator()
                return _items.Values.GetEnumerator();
            IEnumerator IEnumerable.GetEnumerator()
                return _items.Values.GetEnumerator();
            [DataMember]
            public string CacheKey { get; private set; }
            public T this[string cacheKey] { get { return _items[cacheKey]; } }
            public CacheableCollection(string cacheKey, T[] items)
                if (string.IsNullOrWhiteSpace(cacheKey))
                    throw new ArgumentNullException("cacheKey", "Cache key not specified.");
                if (items == null || items.Length == 0)
                    throw new ArgumentNullException("items", "Collection items not specified.");
                this.CacheKey = cacheKey;
                _items = items.ToDictionary(p => p.CacheKey, p => p);
    We tried with the following options on server and client
    Server:
     <advancedProperties>
                <partitionStoreConnectionSettings leadHostManagement="false" />
                <securityProperties mode="None" protectionLevel="None">
                    <authorization>
                        <allow users="[email protected]" />
                        <allow users="[email protected]" />
                    </authorization>
                </securityProperties>
                <transportProperties maxBufferSize="500000000" />
            </advancedProperties>
    Client: 
     <transportProperties connectionBufferSize="131072" maxBufferPoolSize="500000000"
                           maxBufferSize="838860800" maxOutputDelay="2" channelInitializationTimeout="60000"
                           receiveTimeout="600000"/>
    I see different people experiencing different memory size issues. What is the actual memory limit of an  object that can be pushed to Appfabric. 
    Can some one please help ?
    Stack trace:
    Test method Anz.Cre.Pdc.Bootstrapper.Test.LoaderFuncCAOTest.AppFabPushAndRetrieveData threw exception: 
    System.InsufficientMemoryException: Failed to allocate a managed memory buffer of 268435456 bytes. The amount of available memory may be low. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
    System.Runtime.Fx.AllocateByteArray(Int32 size)
    System.Runtime.Fx.AllocateByteArray(Int32 size)
    System.Runtime.InternalBufferManager.PooledBufferManager.TakeBuffer(Int32 bufferSize)
    System.Runtime.BufferedOutputStream.ToArray(Int32& bufferSize)
    System.ServiceModel.Channels.BufferedMessageWriter.WriteMessage(Message message, BufferManager bufferManager, Int32 initialOffset, Int32 maxSizeQuota)
    System.ServiceModel.Channels.BinaryMessageEncoderFactory.BinaryMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
    System.ServiceModel.Channels.FramingDuplexSessionChannel.EncodeMessage(Message message)
    System.ServiceModel.Channels.FramingDuplexSessionChannel.OnSendCore(Message message, TimeSpan timeout)
    System.ServiceModel.Channels.TransportDuplexSessionChannel.OnSend(Message message, TimeSpan timeout)
    System.ServiceModel.Channels.OutputChannel.Send(Message message, TimeSpan timeout)
    Microsoft.ApplicationServer.Caching.WcfClientChannel.SendMessage(EndpointID endpoint, Message message, TimeSpan timeout, WaitCallback callback, Object state, Boolean async)
    Microsoft.ApplicationServer.Caching.WcfClientChannel.Send(EndpointID endpoint, Message message, TimeSpan timeout)
    Microsoft.ApplicationServer.Caching.WcfClientChannel.Send(EndpointID endpoint, Message message)
    Microsoft.ApplicationServer.Caching.DRM.SendRequest(EndpointID address, RequestBody request)
    Microsoft.ApplicationServer.Caching.RequestBody.Send()
    Microsoft.ApplicationServer.Caching.DRM.SendToDestination(RequestBody request, Boolean recordRequest)
    Microsoft.ApplicationServer.Caching.DRM.ProcessRequest(RequestBody request, Boolean recordRequest)
    Microsoft.ApplicationServer.Caching.DRM.ProcessRequest(RequestBody request, Object session)
    Microsoft.ApplicationServer.Caching.RoutingClient.SendMsgAndWait(RequestBody reqMsg)
    Microsoft.ApplicationServer.Caching.DataCache.SendReceive(RequestBody reqMsg)
    Microsoft.ApplicationServer.Caching.DataCache.ExecuteAPI(RequestBody reqMsg)
    Microsoft.ApplicationServer.Caching.DataCache.InternalPut(String key, Object value, DataCacheItemVersion oldVersion, TimeSpan timeout, DataCacheTag[] tags, String region)
    Microsoft.ApplicationServer.Caching.DataCache.Put(String key, Object value, String region)
    Anz.Cre.Pdc.DataCache.DataCacheAccess.Put[T](String cacheName, String regionName, T value) in C:\SVN\2.3_Drop3\app\Src\Anz.Cre.Pdc.DataCache\DataCacheAccess.cs: line 141
    Anz.Cre.Pdc.DataCache.DataCacheAccess.Put[T](String cacheName, String regionName, Boolean flushRegion, T value) in C:\SVN\2.3_Drop3\app\Src\Anz.Cre.Pdc.DataCache\DataCacheAccess.cs: line 372
    Anz.Cre.Pdc.Bootstrapper.Test.LoaderFuncCAOTest.AppFabPushAndRetrieveData() in C:\SVN\2.3_Drop3\app\Src\Anz.Cre.Pdc.Bootstrapper.Test\LoaderFuncCAOTest.cs: line 281

    Essentially what we are trying to do is the following.
    we have different kinds of objects in our baseline. Objects of type CAO, Exposures, Limits that change everyday after close of business day. 
    We wanted to push these different objects in to respective named regions in the cache. 
    Region Name     Objects
    CAO                   ienumerable<caos>
    Exposures           ienumerable<exposures>
    Limits                ienumerable<limits>
    we have a producer that pushes this data in to the cache and consumers of this data acting on the data when its available.
    Now the issue we are facing is when we try to push around 4000 cao objects (roughly in the size of 300MB when serialized using xml) ,we are getting the above error. Increasing the size on the client and cache cluster didnt help.
    The other alternative we were thinking about is chunking and pushing because appfabric doesnt support streaming. We might be able to push this data successfuly if we chunk. But how about the consumers ? wouldnt they face the same memory issue when we use
    getallobjectsinregion ?
    We thought if there was a way to figure out the keys in the region then probably the consumers can get one by one. However there is no such API. 
    The only option i see is using Appfabric notifications which msdn says isnt a reliable way.
    Please help.

  • String & byte

    Hello everybody,
    I'm in this situation: I have a byte array initialized by a list of integers. For some reason, my goal is to convert it to a String and then to get those integers.
    I wrote this simple code:
    byte b[] = { -38, -127, -53, -52, 87, 40, -50, -44, -53, 87, -56, -52, 63, 81, 0, -56, 76, -84, 2, 0, 43, -120, 5, -5 };
    String s = new String(b);
    byte b2[] = s.getBytes();
    for(int i=0; i<b2.length; i++)
    System.out.println((int)(b2));
    but, it works with all ingers except -127, in facts it displays -127 as 63!
    How can I solve this problem? Thanks!

    BalusC wrote:
    I tried ISO-8859-1 here and it worked.
    byte[] bytes = { -38, -127, -53, -52, 87, 40, -50, -44, -53, 87, -56, -52, 63, 81, 0, -56, 76, -84, 2, 0, 43, -120, 5, -5 };
    String string = new String(bytes, "ISO-8859-1");
    for (byte b : string.getBytes("ISO-8859-1")) {
    System.out.print(b + " ");
    All the ISOs 'work' but the point is - what it the OP trying to do?

  • Memory Leak in multidimensional int array?

    I have a simple class
    MyMatrix.h
    @interface MyMatrix : NSObject {
    int twoDMatrix[4][4];
    int threeDMatrix[4][4][2];
    MyMatrix.m
    - init {
    twoDMatrix[0][0] = 0;
    // and so on
    twoDMatrix[3][3] = 1;
    threeDMatrix[0][0][0] = 0;
    // and so on
    threeDMatrix[3][3][1] = 1;
    // and so on
    -(void) dealloc{
    [super dealloc];
    Do you think MyMatrix class will gives Memory Leak ??

    No.

  • "Fatal error: Allowed memory size of 33554432 bytes exhausted" I get this error message when I try to load very large threads at a debate site. What to do?

    "Fatal error: Allowed memory size of 33554432 bytes exhausted"
    I get this error message whenever I try to access very large threads at my favorite debate site using Firefox vs. 4 or 5 on my desktop or laptop computers. I do not get the error using IE8.
    The only fixes I have been able to find are for servers that have Wordpress and php.ini files.

    It works, thanks

  • TNS-01115: OS error 28 creating shared memory segment of 129 bytes

    hi
    we are operating a solaris v5.8 with 10 instances of 10.2.0.1 databases running. each with its own listener. the system shmmni=3600 and using ipcs all are being used causing the error TNS-01115: OS error 28 creating shared memory segment of 129 bytes to occur.
    The kernal parameters were set to be the same as a similiar server we have with the same configuration and more databases and that box uses only 53 memory segments
    Does anyone have any ideas as to what would make this happen?

    i wish i could. there was one db that was not needed so i just shut it down and stopped the listener. then took an ipcs -m reading. it returned 48 rows, instead of 3603 as it did when this particular db was up. in my haste i removed the db as it was not needed so i no longer have the logs to research. too bad on my part.
    well at least i have a fix but have no idea why this happened. thank you for your responses. greatly appreciated.

  • OracleBulkCopy have memory leak  if BatchSize is less than record's count.

    OracleBulkCopy::WriteToServer(IDataReader reader) have memory leak if BatchSize property is less than amount of record which were retrieved from IDataReader.
    We know workaround for that, but when this problem will be fixed?
    Code source at the bottom:
    *****************File::Program.cs*****************
    using System;
    using System.Configuration;
    using System.Data;
    using System.Diagnostics;
    using Oracle.DataAccess.Client;
    namespace WindowsApplication
    static class Program
    private static DataTable _testTable = new DataTable("TestData");
    private static int _batchSize = 10000;
    private static int _totalRecordForTest = 100000;
    private static int _bulkTimeOut = 600;
    private static string _targetConnectionString;
    private static string _targetTableName;
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    _testTable.ReadXmlSchema("tmp.data.schema");
    _testTable.ReadXml("tmp.data");
    _targetConnectionString = ConfigurationManager.AppSettings["targetConnectionString"];
    _targetTableName = ConfigurationManager.AppSettings["targetTableName"];
    _batchSize = int.Parse(ConfigurationManager.AppSettings["batchSize"]);
    _totalRecordForTest = int.Parse(ConfigurationManager.AppSettings["totalRecordForTest"]);
    _bulkTimeOut = int.Parse(ConfigurationManager.AppSettings["bulkTimeOut"]);
    PerformCorrectTest();
    Console.WriteLine("Do you want to perform memory leak test?(If no then click cancel key)");
    if (Console.ReadKey().Key != ConsoleKey.Escape)
    PerformMemoryLeakTest();
    Console.ReadKey();
    _testTable =null;
    public static void PerformCorrectTest()
    Console.WriteLine("Managed memory usage: {0}, unmanaged: {1}", GC.GetTotalMemory(false),
    Process.GetCurrentProcess().WorkingSet64);
    using (VirtualSourceReader wrapper = new VirtualSourceReader(new DataTableReader(_testTable), batchSize, totalRecordForTest))
    wrapper.RowsCopied += RowsCopied;
    using (OracleConnection targetConnection = new OracleConnection(_targetConnectionString))
    targetConnection.Open();
    Console.WriteLine("Bulk insert started at {0}", DateTime.Now);
    OracleBulkCopy bc = null;
    try
    bc = new OracleBulkCopy(targetConnection)
    DestinationTableName = _targetTableName,
    BulkCopyTimeout = _bulkTimeOut,
    BatchSize = _batchSize
    do
    bc.WriteToServer(wrapper);
    } while (wrapper.ResetState());
    finally
    if (null != bc)
    bc.Close();
    bc.Dispose();
    targetConnection.Clone();
    Console.WriteLine("Bulk insert completed at {0}", DateTime.Now);
    wrapper.Close();
    Console.WriteLine("Managed memory usage: {0}, unmanaged: {1}", GC.GetTotalMemory(false),
    Process.GetCurrentProcess().WorkingSet64);
    public static void PerformMemoryLeakTest()
    Console.WriteLine("Managed memory usage: {0}, unmanaged: {1}", GC.GetTotalMemory(false),
    Process.GetCurrentProcess().WorkingSet64);
    using (VirtualSourceReader wrapper = new VirtualSourceReader(new DataTableReader(_testTable), totalRecordForTest, totalRecordForTest))
    using (OracleConnection targetConnection = new OracleConnection(_targetConnectionString))
    targetConnection.Open();
    Console.WriteLine("Bulk insert started at {0}", DateTime.Now);
    OracleBulkCopy bc = null;
    try
    bc = new OracleBulkCopy(targetConnection)
    DestinationTableName = _targetTableName,
    BulkCopyTimeout = _bulkTimeOut,
    BatchSize = _batchSize,
    NotifyAfter = _batchSize,
    bc.OracleRowsCopied += OracleRowsCopied;
    bc.WriteToServer(wrapper);
    finally
    if (null != bc)
    bc.Close();
    bc.Dispose();
    targetConnection.Clone();
    Console.WriteLine("Bulk insert completed at {0}", DateTime.Now);
    wrapper.Close();
    Console.WriteLine("Managed memory usage: {0}, unmanaged: {1}", GC.GetTotalMemory(false),
    Process.GetCurrentProcess().WorkingSet64);
    private static void RowsCopied(object sender, long eventArgs)
    Console.WriteLine("Row Processed {0}. Current time is {1}", eventArgs, DateTime.Now);
    private static void OracleRowsCopied(object sender, OracleRowsCopiedEventArgs eventArgs)
    RowsCopied(sender, eventArgs.RowsCopied);
    *****************File::SourceDataReaderWrap.cs*****************
    using System;
    using System.Collections.Generic;
    using System.Data;
    using Oracle.DataAccess.Client;
    namespace WindowsFormsApplication1
    public delegate void OnRowProcessed(object sender, long rowCount);
    public class SourceDataReaderWrap:IDataReader
    protected IDataReader _originalReader;
    protected readonly int _batchSize;
    protected int _currentSessionRows;
    protected long _rowCount;
    public event OnRowProcessed RowsCopied;
    public SourceDataReaderWrap(IDataReader originalReader, int batchSize)
    _originalReader = originalReader;
    _batchSize = batchSize;
    _rowCount = 0;
    #region Implementation of IDisposable
    /// <summary>
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// </summary>
    /// <filterpriority>2</filterpriority>
    public void Dispose()
    _originalReader.Dispose();
    _originalReader = null;
    if (RowsCopied != null)
    foreach (OnRowProcessed @delegate in new List<Delegate>(RowsCopied.GetInvocationList()))
    RowsCopied -= @delegate;
    #endregion
    #region Implementation of IDataRecord
    /// <summary>
    /// Gets the name for the field to find.
    /// </summary>
    /// <returns>
    /// The name of the field or the empty string (""), if there is no value to return.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public string GetName(int i)
    return _originalReader.GetName(i);
    /// <summary>
    /// Gets the data type information for the specified field.
    /// </summary>
    /// <returns>
    /// The data type information for the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public string GetDataTypeName(int i)
    return _originalReader.GetDataTypeName(i);
    /// <summary>
    /// Gets the <see cref="T:System.Type"/> information corresponding to the type of <see cref="T:System.Object"/> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"/>.
    /// </summary>
    /// <returns>
    /// The <see cref="T:System.Type"/> information corresponding to the type of <see cref="T:System.Object"/> that would be returned from <see cref="M:System.Data.IDataRecord.GetValue(System.Int32)"/>.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public Type GetFieldType(int i)
    return _originalReader.GetFieldType(i);
    /// <summary>
    /// Return the value of the specified field.
    /// </summary>
    /// <returns>
    /// The <see cref="T:System.Object"/> which will contain the field value upon return.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public object GetValue(int i)
    return _originalReader.GetValue(i);
    /// <summary>
    /// Gets all the attribute fields in the collection for the current record.
    /// </summary>
    /// <returns>
    /// The number of instances of <see cref="T:System.Object"/> in the array.
    /// </returns>
    /// <param name="values">An array of <see cref="T:System.Object"/> to copy the attribute fields into.
    /// </param><filterpriority>2</filterpriority>
    public int GetValues(object[] values)
    return _originalReader.GetValues(values);
    /// <summary>
    /// Return the index of the named field.
    /// </summary>
    /// <returns>
    /// The index of the named field.
    /// </returns>
    /// <param name="name">The name of the field to find.
    /// </param><filterpriority>2</filterpriority>
    public int GetOrdinal(string name)
    return _originalReader.GetOrdinal(name);
    /// <summary>
    /// Gets the value of the specified column as a Boolean.
    /// </summary>
    /// <returns>
    /// The value of the column.
    /// </returns>
    /// <param name="i">The zero-based column ordinal.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public bool GetBoolean(int i)
    return _originalReader.GetBoolean(i);
    /// <summary>
    /// Gets the 8-bit unsigned integer value of the specified column.
    /// </summary>
    /// <returns>
    /// The 8-bit unsigned integer value of the specified column.
    /// </returns>
    /// <param name="i">The zero-based column ordinal.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public byte GetByte(int i)
    return _originalReader.GetByte(i);
    /// <summary>
    /// Reads a stream of bytes from the specified column offset into the buffer as an array, starting at the given buffer offset.
    /// </summary>
    /// <returns>
    /// The actual number of bytes read.
    /// </returns>
    /// <param name="i">The zero-based column ordinal.
    /// </param><param name="fieldOffset">The index within the field from which to start the read operation.
    /// </param><param name="buffer">The buffer into which to read the stream of bytes.
    /// </param><param name="bufferoffset">The index for <paramref name="buffer"/> to start the read operation.
    /// </param><param name="length">The number of bytes to read.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
    return _originalReader.GetBytes(i, fieldOffset, buffer, bufferoffset, length);
    /// <summary>
    /// Gets the character value of the specified column.
    /// </summary>
    /// <returns>
    /// The character value of the specified column.
    /// </returns>
    /// <param name="i">The zero-based column ordinal.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public char GetChar(int i)
    return _originalReader.GetChar(i);
    /// <summary>
    /// Reads a stream of characters from the specified column offset into the buffer as an array, starting at the given buffer offset.
    /// </summary>
    /// <returns>
    /// The actual number of characters read.
    /// </returns>
    /// <param name="i">The zero-based column ordinal.
    /// </param><param name="fieldoffset">The index within the row from which to start the read operation.
    /// </param><param name="buffer">The buffer into which to read the stream of bytes.
    /// </param><param name="bufferoffset">The index for <paramref name="buffer"/> to start the read operation.
    /// </param><param name="length">The number of bytes to read.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
    return _originalReader.GetChars(i, fieldoffset, buffer, bufferoffset, length);
    /// <summary>
    /// Returns the GUID value of the specified field.
    /// </summary>
    /// <returns>
    /// The GUID value of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public Guid GetGuid(int i)
    return _originalReader.GetGuid(i);
    /// <summary>
    /// Gets the 16-bit signed integer value of the specified field.
    /// </summary>
    /// <returns>
    /// The 16-bit signed integer value of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public short GetInt16(int i)
    return _originalReader.GetInt16(i);
    /// <summary>
    /// Gets the 32-bit signed integer value of the specified field.
    /// </summary>
    /// <returns>
    /// The 32-bit signed integer value of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public int GetInt32(int i)
    return _originalReader.GetInt32(i);
    /// <summary>
    /// Gets the 64-bit signed integer value of the specified field.
    /// </summary>
    /// <returns>
    /// The 64-bit signed integer value of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public long GetInt64(int i)
    return _originalReader.GetInt64(i);
    /// <summary>
    /// Gets the single-precision floating point number of the specified field.
    /// </summary>
    /// <returns>
    /// The single-precision floating point number of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public float GetFloat(int i)
    return _originalReader.GetFloat(i);
    /// <summary>
    /// Gets the double-precision floating point number of the specified field.
    /// </summary>
    /// <returns>
    /// The double-precision floating point number of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public double GetDouble(int i)
    return _originalReader.GetDouble(i);
    /// <summary>
    /// Gets the string value of the specified field.
    /// </summary>
    /// <returns>
    /// The string value of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public string GetString(int i)
    return _originalReader.GetString(i);
    /// <summary>
    /// Gets the fixed-position numeric value of the specified field.
    /// </summary>
    /// <returns>
    /// The fixed-position numeric value of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public decimal GetDecimal(int i)
    return _originalReader.GetDecimal(i);
    /// <summary>
    /// Gets the date and time data value of the specified field.
    /// </summary>
    /// <returns>
    /// The date and time data value of the specified field.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public DateTime GetDateTime(int i)
    return _originalReader.GetDateTime(i);
    /// <summary>
    /// Returns an <see cref="T:System.Data.IDataReader"/> for the specified column ordinal.
    /// </summary>
    /// <returns>
    /// An <see cref="T:System.Data.IDataReader"/>.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public IDataReader GetData(int i)
    return _originalReader.GetData(i);
    /// <summary>
    /// Return whether the specified field is set to null.
    /// </summary>
    /// <returns>
    /// true if the specified field is set to null; otherwise, false.
    /// </returns>
    /// <param name="i">The index of the field to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    public bool IsDBNull(int i)
    return _originalReader.IsDBNull(i);
    /// <summary>
    /// Gets the number of columns in the current row.
    /// </summary>
    /// <returns>
    /// When not positioned in a valid recordset, 0; otherwise, the number of columns in the current record. The default is -1.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public int FieldCount
    get { return _originalReader.FieldCount; }
    /// <summary>
    /// Gets the column located at the specified index.
    /// </summary>
    /// <returns>
    /// The column located at the specified index as an <see cref="T:System.Object"/>.
    /// </returns>
    /// <param name="i">The zero-based index of the column to get.
    /// </param><exception cref="T:System.IndexOutOfRangeException">The index passed was outside the range of 0 through <see cref="P:System.Data.IDataRecord.FieldCount"/>.
    /// </exception><filterpriority>2</filterpriority>
    object IDataRecord.this[int i]
    get { return _originalReader[i]; }
    /// <summary>
    /// Gets the column with the specified name.
    /// </summary>
    /// <returns>
    /// The column with the specified name as an <see cref="T:System.Object"/>.
    /// </returns>
    /// <param name="name">The name of the column to find.
    /// </param><exception cref="T:System.IndexOutOfRangeException">No column with the specified name was found.
    /// </exception><filterpriority>2</filterpriority>
    object IDataRecord.this[string name]
    get { return _originalReader[name]; }
    #endregion
    #region Implementation of IDataReader
    /// <summary>
    /// Closes the <see cref="T:System.Data.IDataReader"/> Object.
    /// </summary>
    /// <filterpriority>2</filterpriority>
    public void Close()
    _originalReader.Close();
    /// <summary>
    /// Returns a <see cref="T:System.Data.DataTable"/> that describes the column metadata of the <see cref="T:System.Data.IDataReader"/>.
    /// </summary>
    /// <returns>
    /// A <see cref="T:System.Data.DataTable"/> that describes the column metadata.
    /// </returns>
    /// <exception cref="T:System.InvalidOperationException">The <see cref="T:System.Data.IDataReader"/> is closed.
    /// </exception><filterpriority>2</filterpriority>
    public DataTable GetSchemaTable()
    return _originalReader.GetSchemaTable();
    /// <summary>
    /// Gets a value indicating the depth of nesting for the current row.
    /// </summary>
    /// <returns>
    /// The level of nesting.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public int Depth
    get { return _originalReader.Depth; }
    /// <summary>
    /// Gets a value indicating whether the data reader is closed.
    /// </summary>
    /// <returns>
    /// true if the data reader is closed; otherwise, false.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public bool IsClosed
    get { return _originalReader.IsClosed; }
    #endregion
    /// <summary>
    /// Advances the data reader to the next result, when reading the results of batch SQL statements.
    /// </summary>
    /// <returns>
    /// true if there are more rows; otherwise, false.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public bool NextResult()
    throw new NotImplementedException();
    /// <summary>
    /// Advances the <see cref="T:System.Data.IDataReader"/> to the next record.
    /// </summary>
    /// <returns>
    /// true if there are more rows; otherwise, false.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public virtual bool Read()
    if (_batchSize == (_currentSessionRows))
    return false;
    if(_originalReader.Read())
    _currentSessionRows++;
    _rowCount++;
    return true;
    return false;
    /// <summary>
    /// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement.
    /// </summary>
    /// <returns>
    /// The number of rows changed, inserted, or deleted; 0 if no rows were affected or the statement failed; and -1 for SELECT statements.
    /// </returns>
    /// <filterpriority>2</filterpriority>
    public int RecordsAffected
    get { throw new NotImplementedException(); }
    public virtual bool ResetState()
    bool result = _currentSessionRows != 0;
    if (result && RowsCopied != null)
    RowsCopied(this, _rowCount);
    _currentSessionRows = 0;
    return result;
    public class VirtualSourceReader:SourceDataReaderWrap
    private readonly int _totalRecordCount;
    public VirtualSourceReader(IDataReader reader, int batchSize, int totalRecordCount)
    :base(reader, batchSize)
    _totalRecordCount = totalRecordCount;
    public override bool Read()
    if (_rowCount >= totalRecordCount || totalRecordCount <= 0)
    return false;
    if (_rowCount == 0)
    return base.Read();
    if (_batchSize == _currentSessionRows)
    return false;
    _currentSessionRows++;
    _rowCount++;
    return true;
    *****************File::tmp.data**********

    You have problem because the batch size property has value *10000* and amount of records(*50000*) bigger than this value.
    You can retrieve workaround from my post (OracleBulkCopy have memory leak  if BatchSize is less than record's count.

  • Pro*c multithreaded application has memory leak

    Hi there,
    I posted this message a week ago in OCI section, nobody answer me.
    I am really curious if my application has a bug or the pro*c has a bug.
    Anyone can compile the sample code and test it easily.
    I made multithreaded application which queries dynamic SQL, it works.
    But the memory leaks when i query the SQL statement.
    The more memory leaks, the more i query the SQL statement, even same SQL
    statement.
    I check it with top, shell command.
    My machine is SUN E450, Solaris 8. Oracle 9.2.0.1
    Compiler : gcc (GCC) 3.2.2
    I changed source code which is from
    $(ORACLE_HOME)/precomp/demo/proc/sample10.pc
    the sample10 doesn't need to be multithreaded. But i think it has to work
    correctly if i changed it to multithreaded application.
    the make file and source code will be placed below.
    I have to figure out the problem.
    Please help
    Thanks in advance,
    the make file is below
    HOME = /user/jkku
    ORA = $(ORACLE_HOME)
    CC = gcc
    PROC = proc
    LC_INCL = -I$(HOME)/work/dbmss/libs/include
    lc_incl = include=$(HOME)/work/dbmss/libs/include
    SYS_INCL =
    sys_incl =
    ORA_INCL = -I. \
    -I$(ORA)/precomp/public \
    -I$(ORA)/rdbms/public \
    -I$(ORA)/rdbms/demo \
    -I$(ORA)/rdbms/pbsql/public \
    -I$(ORA)/network/public \
    -DSLMXMX_ENABLE -DSLTS_ENABLE -D_SVID_GETTOD
    INCLUDES = $(LC_INCL) $(SYS_INCL) $(ORA_INCL)
    includes = $(lc_incl) $(sys_incl)
    LC_LIBS =
    SYS_LIBS = -lpthread -lsocket -lnsl -lrt
    ORA_LIBS = -L$(ORA)/lib/ -lclntsh
    LIBS = $(LC_LIBS) $(SYS_LIBS) $(ORA_LIBS)
    # Define C Compiler flags
    CFLAGS += -D_Solaris64_ -m64
    CFLAGS += -g -D_REENTRANT
    # Define pro*c Compiler flags
    PROCFLAGS += THREADS=YES
    PROCFLAGS += CPOOL=YES
    # Our object files
    PRECOMPS = sample10.c
    OBJS = sample10.o
    .SUFFIXES: .o .c .pc
    .c.o:
    $(CC) -c $(CFLAGS) $(INCLUDES) $*.c
    .pc.c:
    $(PROC) $(PROCFLAGS) $(includes) $*.pc $*.c
    all: sample10
    sample10: $(PRECOMPS) $(OBJS)
    $(CC) $(CFLAGS) -o sample10 $(OBJS) $(LIBS)
    clean:
    rm -rf *.o sample10 sample10.c
    the source code is below which i changed the oracle sample10.pc to
    multithreaded application.
    Sample Program 10: Dynamic SQL Method 4
    This program connects you to ORACLE using your username and
    password, then prompts you for a SQL statement. You can enter
    any legal SQL statement. Use regular SQL syntax, not embedded SQL.
    Your statement will be processed. If it is a query, the rows
    fetched are displayed.
    You can enter multi-line statements. The limit is 1023 characters.
    This sample program only processes up to MAX_ITEMS bind variables and
    MAX_ITEMS select-list items. MAX_ITEMS is #defined to be 40.
    #include <stdio.h>
    #include <string.h>
    #include <setjmp.h>
    #include <sqlda.h>
    #include <stdlib.h>
    #include <sqlcpr.h>
    /* Maximum number of select-list items or bind variables. */
    #define MAX_ITEMS 40
    /* Maximum lengths of the names of the
    select-list items or indicator variables. */
    #define MAX_VNAME_LEN 30
    #define MAX_INAME_LEN 30
    #ifndef NULL
    #define NULL 0
    #endif
    /* Prototypes */
    #if defined(__STDC__)
    void sql_error(void);
    int oracle_connect(void);
    int alloc_descriptors(int, int, int);
    int get_dyn_statement(void);
    void set_bind_variables(void);
    void process_select_list(void);
    void help(void);
    #else
    void sql_error(/*_ void _*/);
    int oracle_connect(/*_ void _*/);
    int alloc_descriptors(/*_ int, int, int _*/);
    int get_dyn_statement(/* void _*/);
    void set_bind_variables(/*_ void -*/);
    void process_select_list(/*_ void _*/);
    void help(/*_ void _*/);
    #endif
    char *dml_commands[] = {"SELECT", "select", "INSERT", "insert",
    "UPDATE", "update", "DELETE", "delete"};
    EXEC SQL INCLUDE sqlda;
    EXEC SQL INCLUDE sqlca;
    EXEC SQL BEGIN DECLARE SECTION;
    char dyn_statement[1024];
    EXEC SQL VAR dyn_statement IS STRING(1024);
    EXEC SQL END DECLARE SECTION;
    EXEC ORACLE OPTION (ORACA=YES);
    EXEC ORACLE OPTION (RELEASE_CURSOR=YES);
    SQLDA *bind_dp;
    SQLDA *select_dp;
    /* Define a buffer to hold longjmp state info. */
    jmp_buf jmp_continue;
    char *db_uid="dbmuser/dbmuser@dbmdb";
    sql_context ctx;
    int err_sql;
    enum{
    SQL_SUCC=0,
    SQL_ERR,
    SQL_NOTFOUND,
    SQL_UNIQUE,
    SQL_DISCONNECT,
    SQL_NOTNULL
    int main()
    int i;
    EXEC SQL ENABLE THREADS;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    /* Connect to the database. */
    if (connect_database() < 0)
    exit(1);
    EXEC SQL CONTEXT USE :ctx;
    /* Process SQL statements. */
    for (;;)
    /* Allocate memory for the select and bind descriptors. */
    if (alloc_descriptors(MAX_ITEMS, MAX_VNAME_LEN, NAME_LEN) != 0)
    exit(1);
    (void) setjmp(jmp_continue);
    /* Get the statement. Break on "exit". */
    if (get_dyn_statement() != 0)
    break;
    EXEC SQL PREPARE S FROM :dyn_statement;
    EXEC SQL DECLARE C CURSOR FOR S;
    /* Set the bind variables for any placeholders in the
    SQL statement. */
    set_bind_variables();
    /* Open the cursor and execute the statement.
    * If the statement is not a query (SELECT), the
    * statement processing is completed after the
    * OPEN.
    EXEC SQL OPEN C USING DESCRIPTOR bind_dp;
    /* Call the function that processes the select-list.
    * If the statement is not a query, this function
    * just returns, doing nothing.
    process_select_list();
    /* Tell user how many rows processed. */
    for (i = 0; i < 8; i++)
    if (strncmp(dyn_statement, dml_commands, 6) == 0)
    printf("\n\n%d row%c processed.\n", sqlca.sqlerrd[2], sqlca.sqlerrd[2] == 1 ? '\0' : 's');
    break;
    /* Close the cursor. */
    EXEC SQL CLOSE C;
    /* When done, free the memory allocated for pointers in the bind and
    select descriptors. */
    for (i = 0; i < MAX_ITEMS; i++)
    if (bind_dp->V != (char *) 0)
    free(bind_dp->V);
    free(bind_dp->I); /* MAX_ITEMS were allocated. */
    if (select_dp->V != (char *) 0)
    free(select_dp->V);
    free(select_dp->I); /* MAX_ITEMS were allocated. */
    /* Free space used by the descriptors themselves. */
    SQLSQLDAFree(ctx, bind_dp);
    SQLSQLDAFree(ctx, select_dp);
    } /* end of for(;;) statement-processing loop */
    disconnect_database();
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL COMMIT WORK RELEASE;
    puts("\nHave a good day!\n");
    return;
    * Allocate the BIND and SELECT descriptors using sqlald().
    * Also allocate the pointers to indicator variables
    * in each descriptor. The pointers to the actual bind
    * variables and the select-list items are realloc'ed in
    * the set_bind_variables() or process_select_list()
    * routines. This routine allocates 1 byte for select_dp->V
    * and bind_dp->V, so the realloc will work correctly.
    alloc_descriptors(size, max_vname_len, max_iname_len)
    int size;
    int max_vname_len;
    int max_iname_len;
    int i;
    * The first sqlald parameter determines the maximum number of
    * array elements in each variable in the descriptor. In
    * other words, it determines the maximum number of bind
    * variables or select-list items in the SQL statement.
    * The second parameter determines the maximum length of
    * strings used to hold the names of select-list items
    * or placeholders. The maximum length of column
    * names in ORACLE is 30, but you can allocate more or less
    * as needed.
    * The third parameter determines the maximum length of
    * strings used to hold the names of any indicator
    * variables. To follow ORACLE standards, the maximum
    * length of these should be 30. But, you can allocate
    * more or less as needed.
    if ((bind_dp =
    SQLSQLDAAlloc(ctx, size, max_vname_len, max_iname_len)) ==
    (SQLDA *) 0)
    fprintf(stderr,
    "Cannot allocate memory for bind descriptor.");
    return -1; /* Have to exit in this case. */
    if ((select_dp =
    SQLSQLDAAlloc(ctx, size, max_vname_len, max_iname_len)) == (SQLDA *)
    0)
    fprintf(stderr,
    "Cannot allocate memory for select descriptor.");
    return -1;
    select_dp->N = MAX_ITEMS;
    /* Allocate the pointers to the indicator variables, and the
    actual data. */
    for (i = 0; i < MAX_ITEMS; i++) {
    bind_dp->I = (short *) malloc(sizeof (short));
    select_dp->I = (short *) malloc(sizeof(short));
    bind_dp->V = (char *) malloc(1);
    select_dp->V = (char *) malloc(1);
    return 0;
    int get_dyn_statement()
    char *cp, linebuf[256];
    int iter, plsql;
    for (plsql = 0, iter = 1; ;)
    if (iter == 1)
    printf("\nSQL> ");
    dyn_statement[0] = '\0';
    fgets(linebuf, sizeof linebuf, stdin);
    cp = strrchr(linebuf, '\n');
    if (cp && cp != linebuf)
    *cp = ' ';
    else if (cp == linebuf)
    continue;
    if ((strncmp(linebuf, "EXIT", 4) == 0) ||
    (strncmp(linebuf, "exit", 4) == 0))
    return -1;
    else if (linebuf[0] == '?' ||
    (strncmp(linebuf, "HELP", 4) == 0) ||
    (strncmp(linebuf, "help", 4) == 0))
    help();
    iter = 1;
    continue;
    if (strstr(linebuf, "BEGIN") ||
    (strstr(linebuf, "begin")))
    plsql = 1;
    strcat(dyn_statement, linebuf);
    if ((plsql && (cp = strrchr(dyn_statement, '/'))) ||
    (!plsql && (cp = strrchr(dyn_statement, ';'))))
    *cp = '\0';
    break;
    else
    iter++;
    printf("%3d ", iter);
    return 0;
    void set_bind_variables()
    int i, n;
    char bind_var[64];
    /* Describe any bind variables (input host variables) */
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    bind_dp->N = MAX_ITEMS; /* Initialize count of array elements. */
    EXEC SQL DESCRIBE BIND VARIABLES FOR S INTO bind_dp;
    /* If F is negative, there were more bind variables
    than originally allocated by sqlald(). */
    if (bind_dp->F < 0)
    printf ("\nToo many bind variables (%d), maximum is %d\n.",
    -bind_dp->F, MAX_ITEMS);
    return;
    /* Set the maximum number of array elements in the
    descriptor to the number found. */
    bind_dp->N = bind_dp->F;
    /* Get the value of each bind variable as a
    * character string.
    * C contains the length of the bind variable
    * name used in the SQL statement.
    * S contains the actual name of the bind variable
    * used in the SQL statement.
    * L will contain the length of the data value
    * entered.
    * V will contain the address of the data value
    * entered.
    * T is always set to 1 because in this sample program
    * data values for all bind variables are entered
    * as character strings.
    * ORACLE converts to the table value from CHAR.
    * I will point to the indicator value, which is
    * set to -1 when the bind variable value is "null".
    for (i = 0; i < bind_dp->F; i++)
    printf ("\nEnter value for bind variable %.*s: ",
    (int)bind_dp->C, bind_dp->S);
    fgets(bind_var, sizeof bind_var, stdin);
    /* Get length and remove the new line character. */
    n = strlen(bind_var) - 1;
    /* Set it in the descriptor. */
    bind_dp->L = n;
    /* (re-)allocate the buffer for the value.
    sqlald() reserves a pointer location for
    V but does not allocate the full space for
    the pointer. */
    bind_dp->V = (char *) realloc(bind_dp->V, (bind_dp->L + 1));
    /* And copy it in. */
    strncpy(bind_dp->V, bind_var, n);
    /* Set the indicator variable's value. */
    if ((strncmp(bind_dp->V, "NULL", 4) == 0) ||
    (strncmp(bind_dp->V, "null", 4) == 0))
    *bind_dp->I = -1;
    else
    *bind_dp->I = 0;
    /* Set the bind datatype to 1 for CHAR. */
    bind_dp->T = 1;
    return;
    void process_select_list()
    int i, null_ok, precision, scale;
    if ((strncmp(dyn_statement, "SELECT", 6) != 0) &&
    (strncmp(dyn_statement, "select", 6) != 0))
    select_dp->F = 0;
    return;
    /* If the SQL statement is a SELECT, describe the
    select-list items. The DESCRIBE function returns
    their names, datatypes, lengths (including precision
    and scale), and NULL/NOT NULL statuses. */
    select_dp->N = MAX_ITEMS;
    EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;
    /* If F is negative, there were more select-list
    items than originally allocated by sqlald(). */
    if (select_dp->F < 0)
    printf ("\nToo many select-list items (%d), maximum is %d\n",
    -(select_dp->F), MAX_ITEMS);
    return;
    /* Set the maximum number of array elements in the
    descriptor to the number found. */
    select_dp->N = select_dp->F;
    /* Allocate storage for each select-list item.
    sqlprc() is used to extract precision and scale
    from the length (select_dp->L).
    sqlnul() is used to reset the high-order bit of
    the datatype and to check whether the column
    is NOT NULL.
    CHAR datatypes have length, but zero precision and
    scale. The length is defined at CREATE time.
    NUMBER datatypes have precision and scale only if
    defined at CREATE time. If the column
    definition was just NUMBER, the precision
    and scale are zero, and you must allocate
    the required maximum length.
    DATE datatypes return a length of 7 if the default
    format is used. This should be increased to
    9 to store the actual date character string.
    If you use the TO_CHAR function, the maximum
    length could be 75, but will probably be less
    (you can see the effects of this in SQL*Plus).
    ROWID datatype always returns a fixed length of 18 if
    coerced to CHAR.
    LONG and
    LONG RAW datatypes return a length of 0 (zero),
    so you need to set a maximum. In this example,
    it is 240 characters.
    printf ("\n");
    for (i = 0; i < select_dp->F; i++)
    char title[MAX_VNAME_LEN];
    /* Turn off high-order bit of datatype (in this example,
    it does not matter if the column is NOT NULL). */
    sqlnul ((unsigned short *)&(select_dp->T), (unsigned short
    *)&(select_dp->T), &null_ok);
    switch (select_dp->T)
    case 1 : /* CHAR datatype: no change in length
    needed, except possibly for TO_CHAR
    conversions (not handled here). */
    break;
    case 2 : /* NUMBER datatype: use sqlprc() to
    extract precision and scale. */
    sqlprc ((unsigned int *)&(select_dp->L), &precision,
    &scale);
    /* Allow for maximum size of NUMBER. */
    if (precision == 0) precision = 40;
    /* Also allow for decimal point and
    possible sign. */
    /* convert NUMBER datatype to FLOAT if scale > 0,
    INT otherwise. */
    if (scale > 0)
    select_dp->L = sizeof(float);
    else
    select_dp->L = sizeof(int);
    break;
    case 8 : /* LONG datatype */
    select_dp->L = 240;
    break;
    case 11 : /* ROWID datatype */
    case 104 : /* Universal ROWID datatype */
    select_dp->L = 18;
    break;
    case 12 : /* DATE datatype */
    select_dp->L = 9;
    break;
    case 23 : /* RAW datatype */
    break;
    case 24 : /* LONG RAW datatype */
    select_dp->L = 240;
    break;
    /* Allocate space for the select-list data values.
    sqlald() reserves a pointer location for
    V but does not allocate the full space for
    the pointer. */
    if (select_dp->T != 2)
    select_dp->V = (char *) realloc(select_dp->V,
    select_dp->L + 1);
    else
    select_dp->V = (char *) realloc(select_dp->V,
    select_dp->L);
    /* Print column headings, right-justifying number
    column headings. */
    /* Copy to temporary buffer in case name is null-terminated */
    memset(title, ' ', MAX_VNAME_LEN);
    strncpy(title, select_dp->S, select_dp->C);
    if (select_dp->T == 2)
    if (scale > 0)
    printf ("%.*s ", select_dp->L+3, title);
    else
    printf ("%.*s ", select_dp->L, title);
    else
    printf("%-.*s ", select_dp->L, title);
    /* Coerce ALL datatypes except for LONG RAW and NUMBER to
    character. */
    if (select_dp->T != 24 && select_dp->T != 2)
    select_dp->T = 1;
    /* Coerce the datatypes of NUMBERs to float or int depending on
    the scale. */
    if (select_dp->T == 2)
    if (scale > 0)
    select_dp->T = 4; /* float */
    else
    select_dp->T = 3; /* int */
    printf ("\n\n");
    /* FETCH each row selected and print the column values. */
    EXEC SQL WHENEVER NOT FOUND GOTO end_select_loop;
    for (;;)
    EXEC SQL FETCH C USING DESCRIPTOR select_dp;
    /* Since each variable returned has been coerced to a
    character string, int, or float very little processing
    is required here. This routine just prints out the
    values on the terminal. */
    for (i = 0; i < select_dp->F; i++)
    if (*select_dp->I < 0)
    if (select_dp->T == 4)
    printf ("%-*c ",(int)select_dp->L+3, ' ');
    else
    printf ("%-*c ",(int)select_dp->L, ' ');
    else
    if (select_dp->T == 3) /* int datatype */
    printf ("%*d ", (int)select_dp->L,
    *(int *)select_dp->V);
    else if (select_dp->T == 4) /* float datatype */
    printf ("%*.2f ", (int)select_dp->L,
    *(float *)select_dp->V);
    else /* character string */
    printf ("%-*.*s ", (int)select_dp->L,
    (int)select_dp->L, select_dp->V);
    printf ("\n");
    end_select_loop:
    return;
    void help()
    puts("\n\nEnter a SQL statement or a PL/SQL block at the SQL> prompt.");
    puts("Statements can be continued over several lines, except");
    puts("within string literals.");
    puts("Terminate a SQL statement with a semicolon.");
    puts("Terminate a PL/SQL block (which can contain embedded
    semicolons)");
    puts("with a slash (/).");
    puts("Typing \"exit\" (no semicolon needed) exits the program.");
    puts("You typed \"?\" or \"help\" to get this message.\n\n");
    int connect_database()
    err_sql = SQL_SUCC;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    EXEC SQL CONTEXT ALLOCATE :ctx;
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL CONNECT :db_uid;
    if(err_sql != SQL_SUCC){
    printf("err => connect database(ctx:%ld, uid:%s) failed!\n", ctx, db_uid);
    return -1;
    return 1;
    int disconnect_database()
    err_sql = SQL_SUCC;
    EXEC SQL WHENEVER SQLERROR DO sql_error();
    EXEC SQL WHENEVER NOT FOUND DO sql_not_found();
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL COMMIT WORK RELEASE;
    EXEC SQL CONTEXT FREE:ctx;
    return 1;
    void sql_error()
    printf("err => %.*s", sqlca.sqlerrm.sqlerrml, sqlca.sqlerrm.sqlerrmc);
    printf("in \"%.*s...\'\n", oraca.orastxt.orastxtl, oraca.orastxt.orastxtc);
    printf("on line %d of %.*s.\n\n", oraca.oraslnr, oraca.orasfnm.orasfnml,
    oraca.orasfnm.orasfnmc);
    switch(sqlca.sqlcode) {
    case -1: /* unique constraint violated */
    err_sql = SQL_UNIQUE;
    break;
    case -1012: /* not logged on */
    case -1089:
    case -3133:
    case -1041:
    case -3114:
    case -3113:
    /* �6�Ŭ�� shutdown�ǰų� �α��� ���°� �ƴҶ� ��b�� �õ� */
    /* immediate shutdown in progress - no operations are permitted */
    /* end-of-file on communication channel */
    /* internal error. hostdef extension doesn't exist */
    err_sql = SQL_DISCONNECT;
    break;
    case -1400:
    err_sql = SQL_NOTNULL;
    break;
    default:
    err_sql = SQL_ERR;
    break;
    EXEC SQL CONTEXT USE :ctx;
    EXEC SQL WHENEVER SQLERROR CONTINUE;
    EXEC SQL ROLLBACK WORK;
    void sql_not_found()
    err_sql = SQL_NOTFOUND;

    Hi Jane,
    What version of Berkeley DB XML are you using?
    What is your operating system and your hardware platform?
    For how long have been the application running?
    What is your current container size?
    What's set for EnvironmentConfig.setThreaded?
    Do you know if containers have previously not been closed correctly?
    Can you please post the entire error output?
    What's the JDK version, 1.4 or 1.5?
    Thanks,
    Bogdan

Maybe you are looking for

  • SmartView 11.1.2.1.102 corrupts Office 2010.

    Hi We have applied patch set 11.1.2.1.102 recently and installed SmartView Client 11.1.2.1.102 but it is corrupting office 2010 when ever open a excel new page. It seems it is OK with 2003 and 2007. I use 2007 and it works perfectly fine but my busin

  • Problems using a printer shared by a Windows XP PC

    I'm having problems seeing my shared printers on my mac mini. The shared printers are hooked up to a Windows XP PC. There is another PC on the network that is running Windows 7. All 3 machines can access one another with respect to files. I have the

  • JavaMail NoClassDefFoundError

    The following code complies OK but won't run. I get a ava.lang.NoClassDefFoundError: . What's my problem? import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendMail { public static void main (String[] args)

  • SDI or MDI

    Hi, I am implementing plug-ins for Acrobat 8.1.2, Is there any fucntion to find out that, Acrobat is in SDI(Show each document in its own window) mode or MDI mode. Please anybody tell me. Thank you,

  • Mapping Hearder and Item table

    Hi Guys, I have two internal tables one contain header data with over 20 fields and other item with 4 fields. I want to map 2 fields of item table into header table appending into header, but I also want the other fields from header table also to be