Search Results

Search found 12267 results on 491 pages for 'out of memory'.

Page 246/491 | < Previous Page | 242 243 244 245 246 247 248 249 250 251 252 253  | Next Page >

  • C++ polymorphism and slicing

    - by Draco Ater
    The following code, prints out Derived Base Base But I need every Derived object put into User::items, call its own print function, but not the base class one. Can I achieve that without using pointers? If it is not possible, how should I write the function that deletes User::items one by one and frees memory, so that there should not be any memory leaks? #include <iostream> #include <vector> #include <algorithm> using namespace std; class Base{ public: virtual void print(){ cout << "Base" << endl;} }; class Derived: public Base{ public: void print(){ cout << "Derived" << endl;} }; class User{ public: vector<Base> items; void add_item( Base& item ){ item.print(); items.push_back( item ); items.back().print(); } }; void fill_items( User& u ){ Derived d; u.add_item( d ); } int main(){ User u; fill_items( u ); u.items[0].print(); }

    Read the article

  • different thread accessing MemoryStream

    - by Wayne
    There's a bit of code which writes data to a MemoryStream object directly into it's data buffer by calling GetBuffer(). It also uses and updates the Position and SetLength() properties appropriately. This code works purposes 99.9999% of the time. Literally. Only every so many 100,000's of iterations it will barf. The specific problem is that the memory.Position property suddenly returns zero instead of the appropriate value. However, code was added that checks for the 0 and throws an exception which include log of the MemoryStream properties like Position and Length in a separate method. Those return the correct value. Further addition shows that when this rare condition occurs, the memory.Position only has zero inside this particular method. Okay. Obviously, this must be a threading issue. But this code is well locked. However, the nature of this software is that it's organized by "tasks" with a scheduler and so any one of several actual O/S thread may run this code at any give time--but never more than one at a time. So it's my guess that ordinarily it so happens that the same thread keeps getting used for this method and then on a rare occasion a different thread get used. Then due to compiler optimizations, the different thread never gets the correct value. It gets a "stale" value. Ordinarily in a situation like this I would apply a "volatile" keyword to the variable in question. But that (those) variables are inside the MemoryStream object. Does anyone have any other idea? Or does this mean we have to implement our own MemoryStream object? (Just like we end up having to do with practically every collection in .NET?) It's a shame to have such an awesome platform as .NET and have virtually the entire system useless as-is for seriously parallelized applications. If I'm wrong or you have other ideas, please advise. Sincerely, Wayne

    Read the article

  • Best Functional Approach

    - by dbyrne
    I have some mutable scala code that I am trying to rewrite in a more functional style. It is a fairly intricate piece of code, so I am trying to refactor it in pieces. My first thought was this: def iterate(count:Int,d:MyComplexType) = { //Generate next value n //Process n causing some side effects return iterate(count - 1, n) } This didn't seem functional at all to me, since I still have side effects mixed throughout my code. My second thought was this: def generateStream(d:MyComplexType):Stream[MyComplexType] = { //Generate next value n return Stream.cons(n, generateStream(n)) } for (n <- generateStream(initialValue).take(2000000)) { //process n causing some side effects } This seemed like a better solution to me, because at least I've isolated my functional value-generation code from the mutable value-processing code. However, this is much less memory efficient because I am generating a large list that I don't really need to store. This leaves me with 3 choices: Write a tail-recursive function, bite the bullet and refactor the value-processing code Use a lazy list. This is not a memory sensitive app (although it is performance sensitive) Come up with a new approach. I guess what I really want is a lazily evaluated sequence where I can discard the values after I've processed them. Any suggestions?

    Read the article

  • Converting contents of a byte array to wchar_t*

    - by Christopher MacKinnon
    I seem to be having an issue converting a byte array (containing the text from a word document) to a LPTSTR (wchar_t *) object. Every time the code executes, I am getting a bunch of unwanted Unicode characters returned. I figure it is because I am not making the proper calls somewhere, or not using the variables properly, but not quite sure how to approach this. Hopefully someone here can guide me in the right direction. The first thing that happens in we call into C# code to open up Microsoft Word and convert the text in the document into a byte array. byte document __gc[]; document = word->ConvertToArray(filename); The contents of document are as follows: {84, 101, 115, 116, 32, 68, 111, 99, 117, 109, 101, 110, 116, 13, 10} Which ends up being the following string: "Test Document". Our next step is to allocate the memory to store the byte array into a LPTSTR variable, byte __pin * value; value = &document[0]; LPTSTR image; image = (LPTSTR)malloc( document->Length + 1 ); Once we execute the line where we start allocating the memory, our image variable gets filled with a bunch of unwanted Unicode characters: ????????????????? And then we do a memcpy to transfer over all of the data memcpy(image,value,document->Length); Which just causes more unwanted Unicode characters to appear: ????????????????? I figure the issue that we are having is either related to how we are storing the values in the byte array, or possibly when we are copying the data from the byte array to the LPTSTR variable. Any help with explaining what I'm doing wrong, or anything to point me in the right direction will be greatly appreciated.

    Read the article

  • Field Members vs Method Variables?

    - by Braveyard
    Recently I've been thinking about performance difference between class field members and method variables. What exactly I mean is in the example below : Lets say we have a DataContext object for Linq2SQL class DataLayer { ProductDataContext context = new ProductDataContext(); public IQueryable<Product> GetData() { return context.Where(t=>t.ProductId == 2); } } In the example above, context will be stored in heap and the GetData method variables will be removed from Stack after Method is executed. So lets examine the following example to make a distinction : class DataLayer { public IQueryable<Product> GetData() { ProductDataContext context = new ProductDataContext(); return context.Where(t=>t.ProductId == 2); } } (*1) So okay first thing we know is if we define ProductDataContext instance as a field, we can reach it everywhere in the class which means we don't have to create same object instance all the time. But lets say we are talking about Asp.NET and once the users press submit button the post data is sent to the server and the events are executed and the posted data stored in a database via the method above so it is probable that the same user can send different data after one another.If I know correctly after the page is executed, the finalizers come into play and clear things from memory (from heap) and that means we lose our instance variables from memory as well and after another post, DataContext should be created once again for the new page cycle. So it seems the only benefit of declaring it publicly to the whole class is the just number one text above. Or is there something other? Thanks in advance... (If I told something incorrect please fix me.. )

    Read the article

  • On Disk Substring index

    - by emeryc
    I have a file (fasta file to be specific) that I would like to index, so that I can quickly locate any substring within the file and then find the location within the original fasta file. This would be easy to do in many cases, using a Trie or substring array, unfortunately the strings I need to index are 800+ MBs which means that doing them in memory in unacceptable, so I'm looking for a reasonable way to create this index on disk, with minimal memory usage. (edit for clarification) I am only interested in the headers of proteins, so for the largest database I'm interested in, this is about 800 MBs of text. I would like to be able to find an exact substring within O(N) time based on the input string. This must be useable on 32 bit machines as it will be shipped to random people, who are not expected to have 64 bit machines. I want to be able to index against any word break within a line, to the end of the line (though lines can be several MBs long). Hopefully this clarifies what is needed and why the current solutions given are not illuminating. I should also add that this needs to be done from within java, and must be done on client computers on various operating systems, so I can't use any OS Specific solution, and it must be a programatic solution.

    Read the article

  • Copy constructor demo (crashing...)

    - by AKN
    Here is the program... class CopyCon { public: char *name; CopyCon() { name = new char; } CopyCon(const CopyCon &objCopyCon) { name = new char; _tcscpy(name,objCopyCon.name); } ~CopyCon() { if( name != NULL ) { delete name; name = NULL; } } }; int main() { CopyCon objCopyCon1; objCopyCon1.name = "Hai"; CopyCon objCopyCon2(objCopyCon1); objCopyCon1.name = "Hello"; cout<<objCopyCon2.name<<endl; return 0; } Once the code execution completes, when the destructor called, it crashes on 'delete' saying... Debug Error! Program: ... HEAP CORRUPTION DETECTED: after Normal block (#124) at 0x00366990. CRT detected that the application wrote to memory after end of heap buffer. (Press Retry to debug the application) Don't we have to clear the heap memory in destructor. What's wrong with this program? Pls someone help! Copy constructor works perfectly as intended. But still... !?

    Read the article

  • MapView EXC_BAD_ACCESS (SIGSEGV) and KERN_INVALID_ADDRESS

    - by user768113
    I'm having some 'issues' with my application... well, it crashes in an UIViewController that is presented modally, there the user enters information through UITextFields and his location is tracked by a MapView. Lets call this view controller "MapViewController" When the user submits the form, I call a different ViewController - modally again - that processes this info and a third one answers accordingly, then go back to a MenuVC using unwinding segues, which then calls MapViewController and so on. This sequence is repeated many times, but it always crashes in MapViewController. Looking at the crash log, I think that the MapView can be the problem of this or some element in the UI (because of the UIKit framework). I tried to use NSZombie in order to track a memory issue but it doesn't give me a clue about whats happening. Here is the crash log Hardware Model: iPad3,4 Process: MyApp [2253] OS Version: iOS 6.1.3 (10B329) Report Version: 104 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x00000044 Crashed Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 IMGSGX554GLDriver 0x328b9be0 0x328ac000 + 56288 1 IMGSGX554GLDriver 0x328b9b8e 0x328ac000 + 56206deallocated instance 2 IMGSGX554GLDriver 0x328bc2f2 0x328ac000 + 66290 3 IMGSGX554GLDriver 0x328baf44 0x328ac000 + 61252 4 libGPUSupportMercury.dylib 0x370f86be 0x370f6000 + 9918 5 GLEngine 0x34ce8bd2 0x34c4f000 + 629714 6 GLEngine 0x34cea30e 0x34c4f000 + 635662 7 GLEngine 0x34c8498e 0x34c4f000 + 219534 8 GLEngine 0x34c81394 0x34c4f000 + 205716 9 VectorKit 0x3957f4de 0x394c7000 + 754910 10 VectorKit 0x3955552e 0x394c7000 + 582958 11 VectorKit 0x394d056e 0x394c7000 + 38254 12 VectorKit 0x394d0416 0x394c7000 + 37910 13 VectorKit 0x394cb7ca 0x394c7000 + 18378 14 VectorKit 0x394c9804 0x394c7000 + 10244 15 VectorKit 0x394c86a2 0x394c7000 + 5794 16 QuartzCore 0x354a07a4 0x35466000 + 239524 17 QuartzCore 0x354a06fc 0x35466000 + 239356 18 IOMobileFramebuffer 0x376f8fd4 0x376f4000 + 20436 19 IOKit 0x344935aa 0x34490000 + 13738 20 CoreFoundation 0x33875888 0x337e9000 + 575624 21 CoreFoundation 0x338803e4 0x337e9000 + 619492 22 CoreFoundation 0x33880386 0x337e9000 + 619398 23 CoreFoundation 0x3387f20a 0x337e9000 + 614922 24 CoreFoundation 0x337f2238 0x337e9000 + 37432 25 CoreFoundation 0x337f20c4 0x337e9000 + 37060 26 GraphicsServices 0x373ad336 0x373a8000 + 21302 27 UIKit 0x3570e2b4 0x356b7000 + 357044 28 MyApp 0x000ea12e 0xe9000 + 4398 29 MyApp 0x000ea0e4 0xe9000 + 4324 I think thats all, additionally, I would like to ask you: if you are using unwind segues then you are releasing view controllers from the memory heap, right? Meanwhile, performing segues let you instantiate those controllers. Technically, MenuVC should be the only VC alive in the heap during the app life cycle if you understand me.

    Read the article

  • "end()" iterator for back inserters?

    - by Thanatos
    For iterators such as those returned from std::back_inserter(), is there something that can be used as an "end" iterator? This seems a little nonsensical at first, but I have an API which is: template<typename InputIterator, typename OutputIterator> void foo( InputIterator input_begin, InputIterator input_end, OutputIterator output_begin, OutputIterator output_end ); foo performs some operation on the input sequence, generating an output sequence. (Who's length is known to foo but may or may not be equal to the input sequence's length.) The taking of the output_end parameter is the odd part: std::copy doesn't do this, for example, and assumes you're not going to pass it garbage. foo does it to provide range checking: if you pass a range too small, it throws an exception, in the name of defensive programming. (Instead of potentially overwriting random bits in memory.) Now, say I want to pass foo a back inserter, specifically one from a std::vector which has no limit outside of memory constraints. I still need a "end" iterator - in this case, something that will never compare equal. (Or, if I had a std::vector but with a restriction on length, perhaps it might sometimes compare equal?) How do I go about doing this? I do have the ability to change foo's API - is it better to not check the range, and instead provide an alternate means to get the required output range? (Which would be needed anyways for raw arrays, but not required for back inserters into a vector.) This would seem less robust, but I'm struggling to make the "robust" (above) work.

    Read the article

  • How do I implement Hibernate Pagination using a cursor (so the results stay consistent, despite new

    - by hunterae
    Hey all, Is there any way to maintain a database cursor using Hibernate between web requests? Basically, I'm trying to implement pagination, but the data that is being paged is consistently changing (i.e. new records are added into the database). We are trying to set it up such that when you do your initial search (returning a maximum of 5000 results), and you page through the results, those same records always appear on the same page (i.e. we're not continuously running the query each time next and previous page buttons are clicked). The way we're currently implementing this is by merely selecting 5000 (at most) primary keys from the table we're paging, storing those keys in memory, and then just using 20 primary keys at a time to fetch their details from the database. However, we want to get away from having to store these keys in memory and would much prefer a database cursor that we just keep going back to and moving backwards and forwards over the cursor to generate pages. I tried doing this with Hibernate's ScrollableResults but found that I could not call methods like next() and previous() would cause an exception if you within a different web request / Hibernate session (no surprise there). Is there any way to reattach a ScrollableResults object to a Session, much the same way you would reattach a detached database object to make it persistent? Are there any other approaches to implement this data paging with consistent paging results without caching the primary keys?

    Read the article

  • Read whole ASCII file into C++ std::string

    - by Arrieta
    Hello, I need to read a whole file into memory and place it in a C++ std::string. If I were to read it into a char, the answer would be very simple: std::ifstream t; int lenght; t.open("file.txt", "r"); // open input file t.seekg(0, std::ios::end); // go to the end length = t.tellg(); // report location (this is the lenght) t.seekg(0, std::ios::beg); // go back to the beginning buffer = new char[length]; // allocate memory for a buffer of appropriate dimension t.read(buffer, length); // read the whole file into the buffer t.close(); // close file handle // ... do stuff with buffer here ... Now, I want to do the exact same thing, but using a std::string instead of a char. I want to avoid loops, i. e., I don't want to: std::ifstream t; t.open("file.txt", "r"); std::string buffer; std::string line; while(t){ std::getline(t, line); // ... append line to buffer and go on } t.close() any ideas?

    Read the article

  • My kernel only works in block (0,0)

    - by ZeroDivide
    I am trying to write a simple matrixMultiplication application that multiplies two square matrices using CUDA. I am having a problem where my kernel is only computing correctly in block (0,0) of the grid. This is my invocation code: dim3 dimBlock(4,4,1); dim3 dimGrid(4,4,1); //Launch the kernel; MatrixMulKernel<<<dimGrid,dimBlock>>>(Md,Nd,Pd,Width); This is my Kernel function __global__ void MatrixMulKernel(int* Md, int* Nd, int* Pd, int Width) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int bx = blockIdx.x; const int by = blockIdx.y; const int row = (by * blockDim.y + ty); const int col = (bx * blockDim.x + tx); //Pvalue stores the Pd element that is computed by the thread int Pvalue = 0; for (int k = 0; k < Width; k++) { Pvalue += Md[row * Width + k] * Nd[k * Width + col]; } __syncthreads(); //Write the matrix to device memory each thread writes one element Pd[row * Width + col] = Pvalue; } I think the problem may have something to do with memory but I'm a bit lost. What should I do to make this code work across several blocks?

    Read the article

  • What is the fastest way to get a DataTable into SQL Server?

    - by John Gietzen
    I have a DataTable in memory that I need to dump straight into a SQL Server temp table. After the data has been inserted, I transform it a little bit, and then insert a subset of those records into a permanent table. The most time consuming part of this operation is getting the data into the temp table. Now, I have to use temp tables, because more than one copy of this app is running at once, and I need a layer of isolation until the actual insert into the permanent table happens. What is the fastest way to do a bulk insert from a C# DataTable into a SQL Temp Table? I can't use any 3rd party tools for this, since I am transforming the data in memory. My current method is to create a parameterized SqlCommand: INSERT INTO #table (col1, col2, ... col200) VALUES (@col1, @col2, ... @col200) and then for each row, clear and set the parameters and execute. There has to be a more efficient way. I'm able to read and write the records on disk in a matter of seconds...

    Read the article

  • C Programming. How to deep copy a struct?

    - by user69514
    I have the following two structs where "child struct" has a "rusage struct" as an element. Then I create two structs of type "child" let's call them childA and childB How do I copy just the rusage struct from childA to childB? typedef struct{ int numb; char *name; pid_t pid; long userT; long systemT; struct rusage usage; }child; typedef struct{ struct timeval ru_utime; /* user time used */ struct timeval ru_stime; /* system time used */ long ru_maxrss; /* maximum resident set size */ long ru_ixrss; /* integral shared memory size */ long ru_idrss; /* integral unshared data size */ long ru_isrss; /* integral unshared stack size */ long ru_minflt; /* page reclaims */ long ru_majflt; /* page faults */ long ru_nswap; /* swaps */ long ru_inblock; /* block input operations */ long ru_oublock; /* block output operations */ long ru_msgsnd; /* messages sent */ long ru_msgrcv; /* messages received */ long ru_nsignals; /* signals received */ long ru_nvcsw; /* voluntary context switches */ long ru_nivcsw; /* involuntary context switches */ }rusage; I did the following, but I guess it copies the memory location, because if I changed the value of usage in childA, it also changes in childB. memcpy(&childA,&childB, sizeof(rusage)); I know that gives childB all the values from childA. I have already taken care of the others fields in childB, I just need to be able to copy the rusage struct called usage that resides in the "child" struct.

    Read the article

  • Compact data structure for storing a large set of integral values

    - by Odrade
    I'm working on an application that needs to pass around large sets of Int32 values. The sets are expected to contain ~1,000,000-50,000,000 items, where each item is a database key in the range 0-50,000,000. I expect distribution of ids in any given set to be effectively random over this range. The operations I need on the set are dirt simple: Add a new value Iterate over all of the values. There is a serious concern about the memory usage of these sets, so I'm looking for a data structure that can store the ids more efficiently than a simple List<int>or HashSet<int>. I've looked at BitArray, but that can be wasteful depending on how sparse the ids are. I've also considered a bitwise trie, but I'm unsure how to calculate the space efficiency of that solution for the expected data. A Bloom Filter would be great, if only I could tolerate the false negatives. I would appreciate any suggestions of data structures suitable for this purpose. I'm interested in both out-of-the-box and custom solutions. EDIT: To answer your questions: No, the items don't need to be sorted By "pass around" I mean both pass between methods and serialize and send over the wire. I clearly should have mentioned this. There could be a decent number of these sets in memory at once (~100).

    Read the article

  • Threads are blocked in malloc and free, virtual size

    - by Albert Wang
    Hi, I'm running a 64-bit multi-threaded program on the windows server 2003 server (X64), It run into a case that some of the threads seem to be blocked in the malloc or free function forever. The stack trace is like follows: ntdll.dll!NtWaitForSingleObject() + 0xa bytes ntdll.dll!RtlpWaitOnCriticalSection() - 0x1aa bytes ntdll.dll!RtlEnterCriticalSection() + 0xb040 bytes ntdll.dll!RtlpDebugPageHeapAllocate() + 0x2f6 bytes ntdll.dll!RtlDebugAllocateHeap() + 0x40 bytes ntdll.dll!RtlAllocateHeapSlowly() + 0x5e898 bytes ntdll.dll!RtlAllocateHeap() - 0x1711a bytes MyProg.exe!malloc(unsigned __int64 size=0) Line 168 C MyProg.exe!operator new(unsigned __int64 size=1) Line 59 + 0x5 bytes C++ ntdll.dll!NtWaitForSingleObject() ntdll.dll!RtlpWaitOnCriticalSection() ntdll.dll!RtlEnterCriticalSection() ntdll.dll!RtlpDebugPageHeapFree() ntdll.dll!RtlDebugFreeHeap() ntdll.dll!RtlFreeHeapSlowly() ntdll.dll!RtlFreeHeap() MyProg.exe!free(void * pBlock=0x000000007e8e4fe0) C BTW, the param values passed to the new operator is not correct here maybe due to optimization. Also, at the same time, I found in the process Explorer, the virtual size of this program is 10GB, but the private bytes and working set is very small (<2GB). We did have some threads using virtualalloc but in a way that commit the memory in the call, and these threads are not blocked. m_pBuf = VirtualAlloc(NULL, m_size, MEM_COMMIT, PAGE_READWRITE); ...... VirtualFree(m_pBuf, 0, MEM_RELEASE); This looks strange to me, seems a lot of virtual space is reserved but not committed, and malloc/free is blocked by lock. I'm guessing if there's any corruptions in the memory/object, so plan to turn on gflag with pageheap to troubleshoot this. Does anyone has similar experience on this before? Could you share with me so I may get more hints? Thanks a lot!

    Read the article

  • Time gaps between host clEnqueue_xxx calls

    - by dialer
    Consider these OpenCL calls (3 memcpy DtoH, 4313 cl_float elements each): clEnqueueReadBuffer(CommandQueue, SpectrumAbsMem, CL_FALSE, 0, SpectrumMemSize, SpectrumAbs, 0, NULL, NULL); clEnqueueReadBuffer(CommandQueue, SpectrumReMem, CL_FALSE, 0, SpectrumMemSize, SpectrumRe, 0, NULL, NULL); clEnqueueReadBuffer(CommandQueue, SpectrumImMem, CL_FALSE, 0, SpectrumMemSize, SpectrumIm, 0, NULL, NULL); When I analyze these with the NVIDIA visual profiler, I see that the actual memcpy operation only takes 8 us, but there is a significant gap of around 130 us after each memcpy. I'm already using the supposedly asynchronous method (the CL_FALSE in the argument list). When I use only one operation, but with three times the size, the operation is way faster. Why is the time gap between the actual memcpy operations so huge, whereas the gap between the kernel execution (exactly before these three operations) and the first memcpy is only 7us? Can I get rid of it, or do I need to accumulate more data before starting a memcpy? If so, is there a convenient way how I could combine mutliple arrays into a single contiguous block of memory, but still have a cl_mem object as a separate device memory pointer to each section?

    Read the article

  • Best (Java) book for understanding 'under the bonnet' for programming?

    - by Ben
    What would you say is the best book to buy to understand exactly how programming works under the hood in order to increase performance? I've coded in assembly at university, I studied computer architecture and I obviously did high level programming, but what I really dont understand is things like: -what is happening when I perform a cast -whats the difference in performance if I declare something global as opposed to local? -How does the memory layout for an ArrayList compare with a Vector or LinkedList? -Whats the overhead with pointers? -Are locks more efficient than using synchronized? -Would creating my own array using int[] be faster than using ArrayList -Advantages/disadvantages of declaring a variable volatile I have got a copy of Java Performance Tuning but it doesnt go down very low and it contains rather obvious things like suggesting a hashmap instead of using an ArrayList as you can map the keys to memory addresses etc. I want something a bit more Computer Sciencey, linking the programming language to what happens with the assembler/hardware. The reason im asking is that I have an interview coming up for a job in High Frequency Trading and everything has to be as efficient as possible, yet I cant remember every single possible efficiency saving so i'd just like to learn the fundamentals. Thanks in advance

    Read the article

  • Process is killed without a (obvious) reason and program stops working

    - by Krzysiek Gurniak
    Here's what my program is supposed to do: create 4 child processes: process 0 is reading 1 byte at a time from STDIN, then writing it into FIFO process 1 is reading this 1 byte from fifo and write its value as HEX into shared memory process 2 is reading HEX value from shared memory and writing it into pipe finally process 3 is reading from pipe and writing into STDOUT (in my case: terminal) I can't change communication channels. FIFO, then shared memory, then pipes are the only option. My problem: Program stops at random moments when some file is directed into stdin (for example:./program < /dev/urandom). Sometimes after writing 5 HEX values, sometimes after 100. Weird thing is that when it is working and in another terminal I write "pstree -c" there is 1 main process with 4 children processes (which is what I want), but when I write "pstree -c" after it stopped writing (but still runs) there are only 3 child processes. For some reason 1 is gone even though they all have while(1) in them.. I think I might have problem with synchronization here, but I am unable to spot it (I've tried for many hours). Here's the code: #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <sys/shm.h> #include <sys/sem.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/stat.h> #include <string.h> #include <signal.h> #define BUFSIZE 1 #define R 0 #define W 1 // processes ID pid_t p0, p1, p2, p3; // FIFO variables int fifo_fd; unsigned char bufor[BUFSIZE] = {}; unsigned char bufor1[BUFSIZE] = {}; // Shared memory variables key_t key; int shmid; char * tab; // zmienne do pipes int file_des[2]; char bufor_pipe[BUFSIZE*30] = {}; void proces0() { ssize_t n; while(1) { fifo_fd = open("/tmp/fifo",O_WRONLY); if(fifo_fd == -1) { perror("blad przy otwieraniu kolejki FIFO w p0\n"); exit(1); } n = read(STDIN_FILENO, bufor, BUFSIZE); if(n<0) { perror("read error w p0\n"); exit(1); } if(n > 0) { if(write(fifo_fd, bufor, n) != n) { perror("blad zapisu do kolejki fifo w p0\n"); exit(1); } memset(bufor, 0, n); // czyszczenie bufora } close(fifo_fd); } } void proces1() { ssize_t m, x; char wartosc_hex[30] = {}; while(1) { if(tab[0] == 0) { fifo_fd = open("/tmp/fifo", O_RDONLY); // otwiera plik typu fifo do odczytu if(fifo_fd == -1) { perror("blad przy otwieraniu kolejki FIFO w p1\n"); exit(1); } m = read(fifo_fd, bufor1, BUFSIZE); x = m; if(x < 0) { perror("read error p1\n"); exit(1); } if(x > 0) { // Konwersja na HEX if(bufor1[0] < 16) { if(bufor1[0] == 10) // gdy enter { sprintf(wartosc_hex, "0x0%X\n", bufor1[0]); } else { sprintf(wartosc_hex, "0x0%X ", bufor1[0]); } } else { sprintf(wartosc_hex, "0x%X ", bufor1[0]); } // poczekaj az pamiec bedzie pusta (gotowa do zapisu) strcpy(&tab[0], wartosc_hex); memset(bufor1, 0, sizeof(bufor1)); // czyszczenie bufora memset(wartosc_hex, 0, sizeof(wartosc_hex)); // przygotowanie tablicy na zapis wartosci hex x = 0; } close(fifo_fd); } } } void proces2() { close(file_des[0]); // zablokuj kanal do odczytu while(1) { if(tab[0] != 0) { if(write(file_des[1], tab, strlen(tab)) != strlen(tab)) { perror("blad write w p2"); exit(1); } // wyczysc pamiec dzielona by przyjac kolejny bajt memset(tab, 0, sizeof(tab)); } } } void proces3() { ssize_t n; close(file_des[1]); // zablokuj kanal do zapisu while(1) { if(tab[0] == 0) { if((n = read(file_des[0], bufor_pipe, sizeof(bufor_pipe))) > 0) { if(write(STDOUT_FILENO, bufor_pipe, n) != n) { perror("write error w proces3()"); exit(1); } memset(bufor_pipe, 0, sizeof(bufor_pipe)); } } } } int main(void) { key = 5678; int status; // Tworzenie plikow przechowujacych ID procesow int des_pid[2] = {}; char bufor_proces[50] = {}; mknod("pid0", S_IFREG | 0777, 0); mknod("pid1", S_IFREG | 0777, 0); mknod("pid2", S_IFREG | 0777, 0); mknod("pid3", S_IFREG | 0777, 0); // Tworzenie semaforow key_t klucz; klucz = ftok(".", 'a'); // na podstawie pliku i pojedynczego znaku id wyznacza klucz semafora if(klucz == -1) { perror("blad wyznaczania klucza semafora"); exit(1); } semafor = semget(klucz, 1, IPC_CREAT | 0777); // tworzy na podstawie klucza semafor. 1 - ilosc semaforow if(semafor == -1) { perror("blad przy tworzeniu semafora"); exit(1); } if(semctl(semafor, 0, SETVAL, 0) == -1) // ustawia poczatkowa wartosc semafora (klucz, numer w zbiorze od 0, polecenie, argument 0/1/2) { perror("blad przy ustawianiu wartosci poczatkowej semafora"); exit(1); } // Tworzenie lacza nazwanego FIFO if(access("/tmp/fifo", F_OK) == -1) // sprawdza czy plik istnieje, jesli nie - tworzy go { if(mkfifo("/tmp/fifo", 0777) != 0) { perror("blad tworzenia FIFO w main"); exit(1); } } // Tworzenie pamieci dzielonej // Lista pamieci wspoldzielonych, komenda "ipcs" // usuwanie pamieci wspoldzielonej, komenta "ipcrm -m ID_PAMIECI" shmid = shmget(key, (BUFSIZE*30), 0666 | IPC_CREAT); if(shmid == -1) { perror("shmget"); exit(1); } tab = (char *) shmat(shmid, NULL, 0); if(tab == (char *)(-1)) { perror("shmat"); exit(1); } memset(tab, 0, (BUFSIZE*30)); // Tworzenie lacza nienazwanego pipe if(pipe(file_des) == -1) { perror("pipe"); exit(1); } // Tworzenie procesow potomnych if(!(p0 = fork())) { des_pid[W] = open("pid0", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces0 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p0"); exit(1); } close(des_pid[W]); proces0(); } else if(p0 == -1) { perror("blad przy p0 fork w main"); exit(1); } else { if(!(p1 = fork())) { des_pid[W] = open("pid1", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces1 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p1"); exit(1); } close(des_pid[W]); proces1(); } else if(p1 == -1) { perror("blad przy p1 fork w main"); exit(1); } else { if(!(p2 = fork())) { des_pid[W] = open("pid2", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces2 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p2"); exit(1); } close(des_pid[W]); proces2(); } else if(p2 == -1) { perror("blad przy p2 fork w main"); exit(1); } else { if(!(p3 = fork())) { des_pid[W] = open("pid3", O_WRONLY | O_TRUNC | O_CREAT); // 1 - zapis, 0 - odczyt sprintf(bufor_proces, "Proces3 ma ID: %d\n", getpid()); if(write(des_pid[W], bufor_proces, sizeof(bufor_proces)) != sizeof(bufor_proces)) { perror("blad przy zapisie pid do pliku w p3"); exit(1); } close(des_pid[W]); proces3(); } else if(p3 == -1) { perror("blad przy p3 fork w main"); exit(1); } else { // proces macierzysty waitpid(p0, &status, 0); waitpid(p1, &status, 0); waitpid(p2, &status, 0); waitpid(p3, &status, 0); //wait(NULL); unlink("/tmp/fifo"); shmdt(tab); // odlaczenie pamieci dzielonej shmctl(shmid, IPC_RMID, NULL); // usuwanie pamieci wspoldzielonej printf("\nKONIEC PROGRAMU\n"); } } } } exit(0); }

    Read the article

  • Android Signal 11 (SIGSEGV)

    - by Naturjoghurt
    I read many posts here and on other sites, but can not find the problem creating my Error: I use an AsyncTask because I want to easily manipulate the UI Thread before and after Execution. In doInBackground I create a ThreadPoolExecutor and execute Runnables. If I only execute 1 Runnable with the Executor, there is no Problem, but if I execute another Runnable I get following Error: 06-26 18:00:42.288: A/libc(25073): Fatal signal 11 (SIGSEGV) at 0x7f486162 (code=1), thread 25106 (pool-1-thread-2) 06-26 18:00:42.304: D/dalvikvm(25073): GC_CONCURRENT freed 119K, 2% free 8908K/9056K, paused 4ms+4ms, total 45ms 06-26 18:00:42.327: I/System.out(25073): In Check All with Prefix: a and Length: 4 06-26 18:00:42.390: I/DEBUG(126): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 06-26 18:00:42.390: I/DEBUG(126): Build fingerprint: 'google/yakju/maguro:4.2.2/JDQ39/573038:user/release-keys' 06-26 18:00:42.390: I/DEBUG(126): Revision: '9' 06-26 18:00:42.390: I/DEBUG(126): pid: 25073, tid: 25106, name: pool-1-thread-2 >>> de.uni_duesseldorf.cn.distributed_computing2 <<< 06-26 18:00:42.390: I/DEBUG(126): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 7f486162 ... 06-26 18:00:42.538: I/DEBUG(126): memory map around fault addr 7f486162: 06-26 18:00:42.538: I/DEBUG(126): 60292000-60391000 06-26 18:00:42.538: I/DEBUG(126): (no map for address) 06-26 18:00:42.538: I/DEBUG(126): bed14000-bed35000 [stack] I set up the ThreadPoolExecutor like this: // numberOfPackages: Number of Runnables to be executed public void initializeThreadPoolExecutor (int numberOfPackages) { int corePoolSize = Runtime.getRuntime().availableProcessors(); int maxPoolSize = numberOfPackages; long keepAliveTime = 60; final BlockingQueue workingQueue = new LinkedBlockingQueue(); executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.SECONDS, workingQueue); } I have no clue, why it fails when starting the second Thread. Maybe Memory Leaks? Any Help appreciated. Thanks in Advance

    Read the article

  • Detect Application Shutdown in C# NET?

    - by Michael Pfiffer
    I am writing a small console application (will be ran as a service) that basically starts a Java app when it is running, shuts itself down if the Java app closes, and shuts down the Java app if it closes. I think I have the first two working properly, but I don't know how to detect when the .NET application is shutting down so that I can shutdown the Java app prior to that happening. Google search just returns a bunch of stuff about detecting Windows shutting down. Can anyone tell me how I can handle that part and if the rest looks fine? namespace MinecraftDaemon { class Program { public static void LaunchMinecraft(String file, String memoryValue) { String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M "; String args = memParams + "-jar " + file + " nogui"; ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args); processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; try { using (Process minecraftProcess = Process.Start(processInfo)) { minecraftProcess.WaitForExit(); } } catch { // Log Error } } static void Main(string[] args) { Arguments CommandLine = new Arguments(args); if (CommandLine["file"] != null && CommandLine["memory"] != null) { // Launch the Application LaunchMinecraft(CommandLine["file"], CommandLine["memory"]); } else { LaunchMinecraft("minecraft_server.jar", "1024"); } } } }

    Read the article

  • Android: How to do this framing paint?

    - by iDroid Explorer
    I Have Some static images like below: Now, I want is, when i touch on the face or hand, then the selected color should be fill on that skin portion. See below image of result: So how to get the result like above ?? Redo and Undo Functionality Should be also there. I have try with the FloodFill color but doing that i can only able to do color in to the perticular portion. as FloodFill only fill the color till the same pixwl color comes. If the touch place pixel color get change the it will not fill color on it. So Usinf FloodFill i got the result like below image, If i press on the hand, then only hand portion will fill with color, instead of it i want to fill color to the other hand and face also. So Please help me in this case. EDITED After some reply i got the solution like this one. But still there is a memory issue. It consume lots of memory to draw the color. So please can anyone help me for it ?

    Read the article

  • UIImageView and UIScrollView load lot of pictures

    - by Allan.Chen
    In my app, i use UIImageView and UIScrollView to show lot of pictures(Every time there are about 20 pictures and every pictures about 600px*500px and size is about 600KB ), i use for this code to do this function. Here is code: //Here is pictures Data; self.klpArry = self.pictureData; CGSize size = self.klpScrollView1.frame.size; for (int i=0; i < [klpArr count]; i++) { UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake((size.width * i)+300, 20, 546, 546)]; NSString *filePath = [[NSBundle mainBundle] pathForResource:[klpArr objectAtIndex:i] ofType:@"jpg"]; UIImage *imageData = [[UIImage alloc]initWithData:[NSData dataWithContentsOfFile:filePath]]; [iv setImage:imageData]; iv.backgroundColor = [UIColor grayColor]; [self.klpScrollView1 addSubview:iv]; imageData = nil; iv = nil; iv.image = nil; filePath = nil; [imageData release]; [filePath release]; [iv release]; } // show the picture in scrollview; [self.klpScrollView1 setContentSize:CGSizeMake(size.width * numImage, size.height)]; self.klpScrollView1.pagingEnabled = YES; self.klpScrollView1.showsHorizontalScrollIndicator = NO; self.klpScrollView1.backgroundColor = [UIColor grayColor]; But everytime i init this function, the memory will increase about 5MB, Actually i release UIImageView, UIimage and UIScrollView (vi.image=nil,[vi release]) but i doesn't work, it can't release the memory. BTW, i use my friend code first vi.image=nil then vi=nil; but the pictures not to show on scrollview. any one can help me ?? Thx ~~

    Read the article

  • breadth-first traversal of directory tree is not lazy

    - by user855443
    I try to traverse the diretory tree. A naive depth-first traversal seems not to produce the data in a lazy fashion and runs out of memory. I next tried a breadth first approach, which shows the same problem - it uses all the memory available and then crashes. the code i have is: getFilePathBreadtFirst :: FilePath -> IO [FilePath] getFilePathBreadtFirst fp = do fileinfo <- getInfo fp res :: [FilePath] <- if isReadableDirectory fileinfo then do children <- getChildren fp lower <- mapM getFilePathBreadtFirst children return (children ++ concat lower) return (children ++ concat () else return [fp] -- should only return the files? return res getChildren :: FilePath -> IO [FilePath] getChildren path = do names <- getUsefulContents path let namesfull = map (path </>) names return namesfull testBF fn = do -- crashes for /home/frank, does not go to swap fps <- getFilePathBreadtFirst fn putStrLn $ unlines fps I think all the code is either linear or tail recursive, and I would expect that the listing of filenames starts immediately, but in fact it does not. Where is the error in my code and my thinking? where have I lost lazy evaluation?

    Read the article

  • Does Monitor.Wait ensure that fields are re-read?

    - by Marc Gravell
    It is generally accepted (I believe!) that a lock will force any values from fields to be reloaded (essentially acting as a memory-barrier or fence - my terminology in this area gets a bit loose, I'm afraid), with the consequence that fields that are only ever accessed inside a lock do not themselves need to be volatile. (If I'm wrong already, just say!) A good comment was raised here, questioning whether the same is true if code does a Wait() - i.e. once it has been Pulse()d, will it reload fields from memory, or could they be in a register (etc). Or more simply: does the field need to be volatile to ensure that the current value is obtained when resuming after a Wait()? Looking at reflector, Wait calls down into ObjWait, which is managed internalcall (the same as Enter). The scenario in question was: bool closing; public bool TryDequeue(out T value) { lock (queue) { // arbitrary lock-object (a private readonly ref-type) while (queue.Count == 0) { if (closing) { // <==== (2) access field here value = default(T); return false; } Monitor.Wait(queue); // <==== (1) waits here } ...blah do something with the head of the queue } } Obviously I could just make it volatile, or I could move this out so that I exit and re-enter the Monitor every time it gets pulsed, but I'm intrigued to know if either is necessary.

    Read the article

< Previous Page | 242 243 244 245 246 247 248 249 250 251 252 253  | Next Page >