Search Results

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

Page 126/491 | < Previous Page | 122 123 124 125 126 127 128 129 130 131 132 133  | Next Page >

  • AS3/AIR: Managing Run-Time Image Data

    - by grey
    I'm developing a game with AS3 and AIR. I will have a large-ish quantity of images that I need to load for display elements. It would be nice not to embed all of the images that the game needs, thereby avoiding having them all in memory at once. That's okay in smaller projects, but doesn't make sense here. I'm curious about strategies for loading images during run time. Since all of the files are quite small and local ( in my current project ) loading them on request might be the best solution, but I'd like to hear what ideas people have for managing this. For bonus points, I'm also curious about solutions for loading images on-demand server-side as well.

    Read the article

  • Which of these Array Initializations is better in Ruby?

    - by Bragaadeesh
    Hi, Which of these two forms of Array Initialization is better in Ruby? Method 1: DAYS_IN_A_WEEK = (0..6).to_a HOURS_IN_A_DAY = (0..23).to_a @data = Array.new(DAYS_IN_A_WEEK.size).map!{ Array.new(HOURS_IN_A_DAY.size) } DAYS_IN_A_WEEK.each do |day| HOURS_IN_A_DAY.each do |hour| @data[day][hour] = 'something' end end Method 2: DAYS_IN_A_WEEK = (0..6).to_a HOURS_IN_A_DAY = (0..23).to_a @data = {} DAYS_IN_A_WEEK.each do |day| HOURS_IN_A_DAY.each do |hour| @data[day] ||= {} @data[day][hour] = 'something' end end The difference between the first method and the second method is that the second one does not allocate memory initially. I feel the second one is a bit inferior when it comes to performance due to the numerous amount of Array copies that has to happen. However, it is not straight forward in Ruby to find what is happening. So, if someone can explain me which is better, it would be really great! Thanks

    Read the article

  • Qt : crash due to delete (trying to handle exceptions...)

    - by Seub
    I am writing a program with Qt, and I would like it to show a dialog box with a Exit | Restart choice whenever an error is thrown somewhere in the code. What I did causes a crash and I really can't figure out why it happens, I was hoping you could help me understanding what's going on. Here's my main.cpp: #include "my_application.hpp" int main(int argc, char *argv[]) { std::cout << std::endl; My_Application app(argc, argv); return app.exec(); } And here's my_application:hpp: #ifndef MY_APPLICATION_HPP #define MY_APPLICATION_HPP #include <QApplication> class Window; class My_Application : public QApplication { public: My_Application(int& argc, char ** argv); virtual ~My_Application(); virtual bool notify(QObject * receiver, QEvent * event); private: Window *window_; void exit(); void restart(); }; #endif // MY_APPLICATION_HPP Finally, here's my_application.cpp: #include "my_application.hpp" #include "window.hpp" #include <QMessageBox> My_Application::My_Application(int& argc, char ** argv) : QApplication(argc, argv) { window_ = new Window; window_->setAttribute(Qt::WA_DeleteOnClose, false); window_->show(); } My_Application::~My_Application() { delete window_; } bool My_Application::notify(QObject * receiver, QEvent * event) { try { return QApplication::notify(receiver, event); } catch(QString error_message) { window_->setEnabled(false); QMessageBox message_box; message_box.setWindowTitle("Error"); message_box.setIcon(QMessageBox::Critical); message_box.setText("The program caught an unexpected error:"); message_box.setInformativeText("What do you want to do? <br>"); QPushButton *restart_button = message_box.addButton(tr("Restart"), QMessageBox::RejectRole); QPushButton *exit_button = message_box.addButton(tr("Exit"), QMessageBox::RejectRole); message_box.setDefaultButton(restart_button); message_box.exec(); if ((QPushButton *) message_box.clickedButton() == exit_button) { exit(); } else if ((QPushButton *) message_box.clickedButton() == restart_button) { restart(); } } return false; } void My_Application::exit() { window_->close(); //delete window_; return; } void My_Application::restart() { window_->close(); //delete window_; window_ = new Window; window_->show(); return; } Note that the line window_->setAttribute(Qt::WA_DeleteOnClose, false); means that window_ (my main window) won't be deleted when it is closed. The code I've written above works, but as far as I understand, there's a memory leak: I should uncomment the line //delete window_; in My_Application::exit() and My_Application::restart(). But when I do that, the program crashes when I click restart (or exit but who cares). (I'm not sure this is useful, in fact it might be misleading, but here's what my debugger tells me: a segmentation fault occurs in QWidgetPrivate::PaintOnScreen() const which is called by a function called by a function... called by My_Application::notify()) When I do some std::couts, I notice that the program runs through the entire restart() function and in fact through the entire notify() function before it crashes. I have no idea why it crashes. Thanks in advance for your insights! Update: I've noticed that My_Application::notify() is called very often. For example, it is called a bunch of times while the error dialog box is open, also during the execution of the restart function. The crash actually occurs in the subfunction QApplication::notify(receiver, event). This is not too surprising in light of the previous remark (the receiver has probably been deleted) But even if I forbid the function My_Application::notify() to do anything while restart() is executed, it still crashes (after having called My_Application::notify() a bunch of times, like 15 times, isn't that weird)? How should I proceed? Maybe I should say (to make the question slightly more relevant) that my class My_Application also has a "restore" function, which I've not copied here to try to keep things short. If I just had that restart feature I wouldn't bother too much, but I do want to have that restore feature. I should also say that if I keep the code with the "delete window_" commented, the problem is not only a memory leak, it still crashes sometimes apparently. There must surely be a way to fix this! But I'm clueless, I'd really appreciate some help! Thanks in advance.

    Read the article

  • DOMDocument::load in PHP 5

    - by Abs
    Hello all, I open a 10MB+ XML file several times in my script in different functions: $dom = DOMDocument::load( $file ) or die('couldnt open'); 1) Is the above the old style of loading a document? I am using PHP 5. Oppening it statically? 2) Do I need to close the loading of the XML file, if possible? I suspect its causing memory problems because I loop through the nodes of the XML file several thousand times and sometimes my script just ends abruptly. Thanks all for any help

    Read the article

  • How good is the memory mapped Circular Buffer on Wikipedia?

    - by abroun
    I'm trying to implement a circular buffer in C, and have come across this example on Wikipedia. It looks as if it would provide a really nice interface for anyone reading from the buffer, as reads which wrap around from the end to the beginning of the buffer are handled automatically. So all reads are contiguous. However, I'm a bit unsure about using it straight away as I don't really have much experience with memory mapping or virtual memory and I'm not sure that I fully understand what it's doing. What I think I understand is that it's mapping a shared memory file the size of the buffer into memory twice. Then, whenever data is written into the buffer it appears in memory in 2 places at once. This allows all reads to be contiguous. What would be really great is if someone with more experience of POSIX memory mapping could have a quick look at the code and tell me if the underlying mechanism used is really that efficient. Am I right in thinking for example that the file in /dev/shm used for the shared memory always stays in RAM or could it get written to the hard drive (performance hit) at some point? Are there any gotchas I should be aware of? As it stands, I'm probably going to use a simpler method for my current project, but it'd be good to understand this to have it in my toolbox for the future. Thanks in advance for your time.

    Read the article

  • What does the Kernel Virtual Memory of each process contain?

    - by claws
    When say 3 programs (executables) are loaded into memory the layout might look something like this: I've following questions: Is the concept of Virtual Memory limited to user processes? Because, I am wondering where does the Operating System Kernel, Drivers live? How is its memory layout? I know its operating system specific make your choice (windows/linux). They say, on a 32 bit machine in a 4GB address space. Half of it (or more recently 1GB) is occupied by kernel. I can see in this diagram that "Kernel Virtual memory" is occupying 0xc0000000 - 0xffffffff (= 1 GB). Are they talking about this? or is it something else? Just want to confirm. What exactly does the Kernel Virtual Memory of each of these processes contain? What is its layout? When we do IPC we talk about shared memory. I don't see any memory shared between these processes. Where does it live? Resources (files, registries in windows) are global to all processes. So, the resource/file handle table must be in some global space. Which area would that be in? Where can I know more about this kernel side stuff.

    Read the article

  • AIX Checklist for stable obiee deployment

    - by user554629
    Common AIX configuration issues     ( last updated 27 Aug 2012 ) OBIEE is a complicated system with many moving parts and connection points.The purpose of this article is to provide a checklist to discuss OBIEE deployment with your systems administrators. The information in this article is time sensitive, and updated as I discover new  issues or details. What makes OBIEE different? When Tech Support suggests AIX component upgrades to a stable, locked-down production AIX environment, it is common to get "push back".  "Why is this necessary?  We aren't we seeing issues with other software?"It's a fair question that I have often struggled to answer; here are the talking points: OBIEE is memory intensive.  It is the entire purpose of the software to trade memory for repetitive, more expensive database requests across a network. OBIEE is implemented in C++ and is very dependent on the C++ runtime to behave correctly. OBIEE is aggressively thread efficient;  if atomic operations on a particular architecture do not work correctly, the software crashes. OBIEE dynamically loads third-party database client libraries directly into the nqsserver process.  If the library is not thread-safe, or corrupts process memory the OBIEE crash happens in an unrelated part of the code.  These are extremely difficult bugs to find. OBIEE software uses 99% common source across multiple platforms:  Windows, Linux, AIX, Solaris and HPUX.  If a crash happens on only one platform, we begin to suspect other factors.  load intensity, system differences, configuration choices, hardware failures.  It is rare to have a single product require so many diverse technical skills.   My role in support is to understand system configurations, performance issues, and crashes.   An analyst trained in Business Analytics can't be expected to know AIX internals in the depth required to make configuration choices.  Here are some guidelines. AIX C++ Runtime must be at  version 11.1.0.4$ lslpp -L | grep xlC.aixobiee software will crash if xlC.aix.rte is downlevel;  this is not a "try it" suggestion.Nov 2011 11.1.0.4 version  is appropriate for all AIX versions ( 5, 6, 7 )Download from here:https://www-304.ibm.com/support/docview.wss?uid=swg24031426 No reboot is necessary to install, it can even be installed while applications are using the current version.Restart the apps, and they will pick up the latest version. AIX 5.3 Technology Level 12 is required when running on Power5,6,7 processorsAIX 6.1 was introduced with the newer Power chips, and we have seen no issues with 6.1 or 7.1 versions.Customers with an unstable deployment, dozens of unexplained crashes, became stable after the upgrade.If your AIX system is 5.3, the minimum TL level should be at or higher than this:$ oslevel -s  5300-12-03-1107IBM typically supports only the two latest versions of AIX ( 6.1 and 7.1, for example).  AIX 5.3 is still supported and popular running in an LPAR. obiee userid limits$ ulimit -Ha  ( hard limits )$ ulimit -a   ( default limits )core file size (blocks)     unlimiteddata seg size (kbytes)      unlimitedfile size (blocks)          unlimitedmax memory size (kbytes)    unlimitedopen files                  10240 cpu time (seconds)          unlimitedvirtual memory (kbytes)     unlimitedIt is best to establish the values in /etc/security/limitsroot user is needed to observe and modify this file.If you modify a limit, you will need to relog in to change it again.  For example,$ ulimit -c 0$ ulimit -c 2097151cannot modify limit: Operation not permitted$ ulimit -c unlimited$ ulimit -c0There are only two meaningful values for ulimit -c ; zero or unlimited.Anything else is likely to produce a truncated core file that cannot be analyzed. Deploy 32-bit or 64-bit ?Early versions of OBIEE offered 32-bit or 64-bit choice to AIX customers.The 32-bit choice was needed if a database vendor did not supply a 64-bit client library.That's no longer an issue and beginning with OBIEE 11, 32-bit code is no longer shipped.A common error that leads to "out of memory" conditions to to accept the 32-bit memory configuration choices on 64-bit deployments.  The significant configuration choices are: Maximum process data (heap) size is in an AIX environment variableLDR_CNTRL=IGNOREUNLOAD@LOADPUBLIC@PREREAD_SHLIB@MAXDATA=0x... Two thread stack sizes are made in obiee NQSConfig.INI[ SERVER ]SERVER_THREAD_STACK_SIZE = 0;DB_GATEWAY_THREAD_STACK_SIZE = 0; Sort memory in NQSConfig.INI[ GENERAL ]SORT_MEMORY_SIZE = 4 MB ;SORT_BUFFER_INCREMENT_SIZE = 256 KB ; Choosing a value for MAXDATA:0x080000000  2GB Default maximum 32-bit heap size ( 8 with 7 zeros )0x100000000  4GB 64-bit breaking even with 32-bit ( 1 with 8 zeros )0x200000000  8GB 64-bit double 32-bit max0x400000000 16GB 64-bit safetyUsing 2GB heap size for a 64-bit process will almost certainly lead to an out-of-memory situation.Registers are twice as big ... consume twice as much memory in the heap.Upgrading to a 4GB heap for a 64-bit process is just "breaking even" with 32-bit.A 32-bit process is constrained by the 32-bit virtual addressing limits.  Heap memory is used for dynamic requirements of obiee software, thread stacks for each of the configured threads, and sometimes for shared libraries. 64-bit processes are not constrained in this way;  extra heap space can be configured for safety against a query that might create a sudden requirement for excessive storage.  If the storage is not available, this query might crash the whole server and disrupt existing users.There is no performance penalty on AIX for configuring more memory than required;  extra memory can be configured for safety.  If there are no other considerations, start with 8GB.Choosing a value for Thread Stack size:zero is the value documented to select an appropriate default for thread stack size.  My preference is to change this to an absolute value, even if you intend to use the documented default;  it provides better documentation and removes the "surprise" factor.There are two thread types that can be configured. GATEWAY is used by a thread pool to call a database client library to establish a DB connection.The default size is 256KB;  many customers raise this to 512KB ( no performance penalty for over-configuring ). This value must be set to 1 MB if Teradata connections are used. SERVER threads are used to run queries.  OBIEE uses recursive algorithms during the analysis of query structures which can consume significant thread stack storage.  It's difficult to provide guidance on a value that depends on data and complexity.  The general notion is to provide more space than you think you need,  "double down" and increase the value if you run out, otherwise inspect the query to understand why it is too complex for the thread stack.  There are protections built into the software to abort a single user query that is too complex, but the algorithms don't cover all situations.256 KB  The default 32-bit stack size.  Many customers increased this to 512KB on 32-bit.  A 64-bit server is very likely to crash with this value;  the stack contains mostly register values, which are twice as big.512 KB  The documented 64-bit default.  Some early releases of obiee didn't set this correctly, resulting in 256KB stacks.1 MB  The recommended 64-bit setting.  If your system only ever uses 512KB of stack space, there is no performance penalty for using 1MB stack size.2 MB  Many large customers use this value for safety.  No performance penalty.nqscheduler does not use the NQSConfig.INI file to set thread stack size.If this process crashes because the thread stack is too small, use this to set 2MB:export OBI_BACKGROUND_STACK_SIZE=2048 Shared libraries are not (shared) When application libraries are loaded at run-time, AIX makes a decision on whether to load the libraries in a "public" memory segment.  If the filesystem library permissions do not have the "Read-Other" permission bit, AIX loads the library into private process memory with two significant side-effects:* The libraries reduce the heap storage available.      Might be significant in 32-bit processes;  irrelevant in 64-bit processes.* Library code is loaded into multiple real pages for execution;  one copy for each process.Multiple execution images is a significant issue for both 32- and 64-bit processes.The "real memory pages" saved by using public memory segments is a minor concern.  Today's machines typically have plenty of real memory.The real problem with private copies of libraries is that they consume processor cache blocks, which are limited.   The same library instructions executing in different real pages will cause memory delays as the i-cache ( instruction cache 128KB blocks) are refreshed from real memory.   Performance loss because instructions are delayed is something that is difficult to measure without access to low-level cache fault data.   The machine just appears to be running slowly for no observable reason.This is an easy problem to detect, and an easy problem to correct.Detection:  "genld -l" AIX command produces a list of the libraries used by each process and the AIX memory address where they are loaded.32-bit public segment is 13 ( "dxxxxxxx" ).   private segments are 2-a.64-bit public segment is 9 ( "9xxxxxxxxxxxxxxx") ; private segment is 8.genld -l | grep -v ' d| 9' | sort +2provides a list of privately loaded libraries. Repair: chmod o+r <libname>AIX shared libraries will have a suffix of ".so" or ".a".Another technique is to change all libraries in a selected directory to repair those that might not be currently loaded.   The usual directories that need repair are obiee code, httpd code and plugins, database client libraries and java.chmod o+r /shr/dir/*.a /shr/dir/*.so Configure your system for diagnosticsProduction systems shouldn't crash, and yet bad things happen to good software.If obiee software crashes and produces a core, you should configure your system for reliable transfer of the failing conditions to Oracle Tech Support.  Here's what we need to be able to diagnose a core file from your system.* fullcore enabled. chdev -lsys0 -a fullcore=true* core naming enabled. chcore -n on -d* ulimit must not truncate core. see item 3.* pstack.sh is used to capture core documentation.* obidoc is used to capture current AIX configuration.* snapcore  AIX utility captures core and libraries. Use the proper syntax. $ snapcore -r corename executable-fullpath   /tmp/snapcore will contain the .pax.Z output file.  It is compressed.* If cores are directed to a common directory, ensure obiee userid can write to the directory.  ( chcore -p /cores -d ; chmod 777 /cores )The filesystem must have sufficient space to hold a crashing obiee application.Use:  df -k  Check the "Free" column ( not "% Used" )  8388608 is 8GB. Disable Oracle Client Library signal handlingThe Oracle DB Client Library is frequently distributed with the sqlplus development kit.By default, the library enables a signal handler, which will document a call stack if the application crashes.   The signal handler is not needed, and definitely disruptive to obiee diagnostics.   It needs to be disabled.   sqlnet.ora is typically located at:   $ORACLE_HOME/network/admin/sqlnet.oraAdd this line at the top of the file:   DIAG_SIGHANDLER_ENABLED=FALSE Disable async query in the RPD connection pool.This might be an obiee 10.1.3.4 issue only ( still checking  )."async query" must be disabled in the connection pools.It was designed to enable query cancellation to a database, and turned out to have too many edge conditions in normal communication that produced random corruption of data and crashes.  Please ensure it is turned off in the RPD. Check AIX error report (errpt).Errors external to obiee applications can trigger crashes.  $ /bin/errpt -aHardware errors ( firmware, adapters, disks ) should be reported to IBM support.All application core files are recorded by AIX;  the most recent ones are listed first. Reserved for something important to say.

    Read the article

  • Wrapping malloc - C

    - by Appu
    I am a beginner in C. While reading git's source code, I found this wrapper function around malloc. void *xmalloc(size_t size) { void *ret = malloc(size); if (!ret && !size) ret = malloc(1); if (!ret) { release_pack_memory(size, -1); ret = malloc(size); if (!ret && !size) ret = malloc(1); if (!ret) die("Out of memory, malloc failed"); } #ifdef XMALLOC_POISON memset(ret, 0xA5, size); #endif return ret; } Questions I couldn't understand why are they using malloc(1)? What does release_pack_memory does and I can't find this functions implementation in the whole source code. What does the #ifdef XMALLOC_POISON memset(ret, 0xA5, size); does? I am planning to reuse this function on my project. Is this a good wrapper around malloc? Any help would be great.

    Read the article

  • Automatically calling OnDetaching() for Silverlight Behaviors

    - by Dan Auclair
    I am using several Blend behaviors and triggers on a silverlight control. I am wondering if there is any mechanism for automatically detaching or ensuring that OnDetaching() is called for a behavior or trigger when the control is no longer being used (i.e. removed from the visual tree). My problem is that there is a managed memory leak with the control because of one of the behaviors. The behavior subscribes to an event on some long-lived object in the OnAttached() override and should be unsubscribing to that event in the OnDetaching() override so that it can become a candidate for garbage collection. However, OnDetaching() never seems to be getting called when I remove the control from the visual tree... the only way I can get it to happen is by explicit detaching the behavior BEFORE removing the control and then it is properly garbage collected. Right now my only solution was to create a public method in the code-behind for the control that can go through and detach any known behaviors that would cause garbage collection problems. It would be up to the client code to know to call this before removing the control from the panel. I don't really like this approach, so I am looking for some automatic way of doing this that I am overlooking or a better suggestion. public void DetachBehaviors() { foreach (var behavior in Interaction.GetBehaviors(this.LayoutRoot)) { behavior.Detach(); } //... //continue detaching all known problematic behaviors.... }

    Read the article

  • Do the ‘up to date’ guarantees for values of Java's final fields extend to indirect references?

    - by mattbh
    The Java language spec defines semantics of final fields in section 17.5: The usage model for final fields is a simple one. Set the final fields for an object in that object's constructor. Do not write a reference to the object being constructed in a place where another thread can see it before the object's constructor is finished. If this is followed, then when the object is seen by another thread, that thread will always see the correctly constructed version of that object's final fields. It will also see versions of any object or array referenced by those final fields that are at least as up-to-date as the final fields are. My question is - does the 'up-to-date' guarantee extend to the contents of nested arrays, and nested objects? An example scenario: Thread A constructs a HashMap of ArrayLists, then assigns the HashMap to final field 'myFinal' in an instance of class 'MyClass' Thread B sees a (non-synchronized) reference to the MyClass instance and reads 'myFinal', and accesses and reads the contents of one of the ArrayLists In this scenario, are the members of the ArrayList as seen by Thread B guaranteed to be at least as up to date as they were when MyClass's constructor completed? I'm looking for clarification of the semantics of the Java Memory Model and language spec, rather than alternative solutions like synchronization. My dream answer would be a yes or no, with a reference to the relevant text.

    Read the article

  • Delete array of size 1

    - by Arne
    This is possibly a candidate for a one-line answer. I would like know it anyway.. I am writing a simple circular buffer and for some reasons that are not important for the question I need to implement it using an array of doubles. In fact I have not investiated other ways to do it, but since an array is required anyway I have not spent much time on looking for alternatives. template<typename T> class CircularBuffer { public: CircularBuffer(unsigned int size); ~CircularBuffer(); void Resize(unsigned int new_size); ... private: T* buffer; unsigned int buffer_size; }; Since I need to have the buffer dynamically sized the buffer_size is neither const nor a template parameter. Now the question: During construction and in function Resize(int) I only require the size to be at least one, although a buffer of size one is effectively no longer a buffer. Of course using a simple double instead would be more appropriate but anyway. Now when deleting the internal buffer in the destructor - or in function resize for that matter - I need to delete the allocated memory. Question is, how? First candidate is of course delete[] buffer; but then again, if I have allocated a buffer of size one, that is if the pointer was aquired with buffer = new T[0], is it still appropriate to call delete[] on the pointer or do I need to call delete buffer; (without brackets) ? Thanks, Arne

    Read the article

  • IPhone custom UITableViewCell Reloading

    - by Steblo
    Hi, currently I'm struggling with this problem: I got a UITableViewController that displays a tableView with different custom cells. One custom cell displays a number (by a label). If you click on this cell, the navigationController moves to a UIPicker where the user can select the number to be displayes. If the user moves back, the cell should display the updated value. Problem: I managed to reload the cells by calling - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.tableView reloadData]; } in the UITableViewController. This works only, if I don't use dequeueReusableCellWithIdentifier for the cell (tables won't show updates otherwise). But in this case, memory usage grows and grows... In addition, the program crashes after about 15 movements to pickerView and back - I think because the cell that should be reloaded is already released. How can I update a reusable custom cell every time the view appears ? What is the best solution ? I think retaining cells should not be used ?

    Read the article

  • C++ stringstream, string, and char* conversion confusion

    - by Graphics Noob
    My question can be boiled down to, where does the string returned from stringstream.str().c_str() live in memory, and why can't it be assigned to a const char*? This code example will explain it better than I can #include <string> #include <sstream> #include <iostream> using namespace std; int main() { stringstream ss("this is a string\n"); string str(ss.str()); const char* cstr1 = str.c_str(); const char* cstr2 = ss.str().c_str(); cout << cstr1 // Prints correctly << cstr2; // ERROR, prints out garbage system("PAUSE"); return 0; } The assumption that stringstream.str().c_str() could be assigned to a const char* led to a bug that took me a while to track down. For bonus points, can anyone explain why replacing the cout statement with cout << cstr // Prints correctly << ss.str().c_str() // Prints correctly << cstr2; // Prints correctly (???) prints the strings correctly? I'm compiling in Visual Studio 2008.

    Read the article

  • Java: volatile guarantees and out-of-order execution

    - by WizardOfOdds
    Note that this question is solely about the volatile keyword and the volatile guarantees: it is not about the synchronized keyword (so please don't answer "you must use synchronize" for I don't have any issue to solve: I simply want to understand the volatile guarantees (or lack of guarantees) regarding out-of-order execution). Say we have an object containing two volatile String references that are initialized to null by the constructor and that we have only one way to modify the two String: by calling setBoth(...) and that we can only set their references afterwards to non-null reference (only the constructor is allowed to set them to null). For example (it's just an example, there's no question yet): public class SO { private volatile String a; private volatile String b; public SO() { a = null; b = null; } public void setBoth( @NotNull final String one, @NotNull final String two ) { a = one; b = two; } public String getA() { return a; } public String getB() { return b; } } In setBoth(...), the line assigning the non-null parameter "a" appears before the line assigning the non-null parameter "b". Then if I do this (once again, there's no question, the question is coming next): if ( so.getB() != null ) { System.out.println( so.getA().length ); } Am I correct in my understanding that due to out-of-order execution I can get a NullPointerException? In other words: there's no guarantee that because I read a non-null "b" I'll read a non-null "a"? Because due to out-of-order (multi)processor and the way volatile works "b" could be assigned before "a"? volatile guarantees that reads subsequent to a write shall always see the last written value, but here there's an out-of-order "issue" right? (once again, the "issue" is made on purpose to try to understand the semantics of the volatile keyword and the Java Memory Model, not to solve a problem).

    Read the article

  • Weak event handler model for use with lambdas

    - by Benjol
    OK, so this is more of an answer than a question, but after asking this question, and pulling together the various bits from Dustin Campbell, Egor, and also one last tip from the 'IObservable/Rx/Reactive framework', I think I've worked out a workable solution for this particular problem. It may be completely superseded by IObservable/Rx/Reactive framework, but only experience will show that. I've deliberately created a new question, to give me space to explain how I got to this solution, as it may not be immediately obvious. There are many related questions, most telling you you can't use inline lambdas if you want to be able to detach them later: Weak events in .Net? Unhooking events with lambdas in C# Can using lambdas as event handlers cause a memory leak? How to unsubscribe from an event which uses a lambda expression? Unsubscribe anonymous method in C# And it is true that if YOU want to be able to detach them later, you need to keep a reference to your lambda. However, if you just want the event handler to detach itself when your subscriber falls out of scope, this answer is for you.

    Read the article

  • LocalAlloc and LocalRealloc usage

    - by PaulH
    I have a Visual Studio 2008 C++ Windows Mobile 6 application where I'm using a FindFirst() / FindNext() style API to get a collection of items. I do not know how many items will be in the list ahead of time. So, I would like to dynamically allocate an array for these items. Normally, I would use a std::vector<>, but, for other reasons, that's not an option for this application. So, I'm using LocalAlloc() and LocalReAlloc(). What I'm not clear on is if this memory should be marked fixed or moveable. The application runs fine either way. I'm just wondering what's 'correct'. int count = 0; INFO_STRUCT* info = ( INFO_STRUCT* )LocalAlloc( LHND, sizeof( INFO_STRUCT ) ); while( S_OK == GetInfo( &info[ count ] ) { ++count; info = ( INFO_STRUCT* )LocalRealloc( info, sizeof( INFO_STRUCT ) * ( count + 1 ), LHND ); } if( count > 0 ) { // use the data in some interesting way... } LocalFree( info ); Thanks, PaulH

    Read the article

  • understanding valgrind output

    - by sbsp
    Hi, i made a post earlier asking about checking for memory leaks etc, i did say i wasnt to familiar with the terminal in linux but someone said to me it was easy with valgrind i have managed to get it running etc but not to sure what the output means. Glancing over, all looks good to me but would like to run it past you experience folk for confirmation if possible. THe output is as follows ^C==2420== ==2420== HEAP SUMMARY: ==2420== in use at exit: 2,240 bytes in 81 blocks ==2420== total heap usage: 82 allocs, 1 frees, 2,592 bytes allocated ==2420== ==2420== LEAK SUMMARY: ==2420== definitely lost: 0 bytes in 0 blocks ==2420== indirectly lost: 0 bytes in 0 blocks ==2420== possibly lost: 0 bytes in 0 blocks ==2420== still reachable: 2,240 bytes in 81 blocks ==2420== suppressed: 0 bytes in 0 blocks ==2420== Reachable blocks (those to which a pointer was found) are not shown. ==2420== To see them, rerun with: --leak-check=full --show-reachable=yes ==2420== ==2420== For counts of detected and suppressed errors, rerun with: -v ==2420== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 13 from 8) Is all good here? the only thing concerning me is the still reachable part. Is that ok? Thanks everyone

    Read the article

  • detecting double free object, release or not release ...

    - by mongeta
    Hello, If we have this code in our interface .h file: NSString *fieldNameToStoreModel; NSFetchedResultsController *fetchedResultsController; NSManagedObjectContext *managedObjectContext; DataEntered *dataEntered; In our implementation file .m we must have: - (void)dealloc { [fieldNameToStoreModel release]; [fetchedResultsController release]; [managedObjectContext release]; [dataEntered release]; [super dealloc]; } The 4 objects are assigned from a previous UIViewController, like this: UIViewController *detailViewController; detailViewController = [[CarModelSelectViewController alloc] initWithStyle:UITableViewStylePlain]; ((CarModelSelectViewController *)detailViewController).dataEntered = self.dataEntered; ((CarModelSelectViewController *)detailViewController).managedObjectContext = self.managedObjectContext; ((CarModelSelectViewController *)detailViewController).fieldNameToStoreModel = self.fieldNameToStoreModel; [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; The objects that now live in the new UIViewController, are the same as the previous UIViewController, and I can't release them in the new UIViewController ? The problems is that sometimes, my app crashes when I leave the new UIViewController and go to the previous one, not always. Normally the error that I'm getting is a double free object. I've used the malloc_error_break but I'm still not sure wich object is. Sometimes I can go from the previous UIViewController to the next one and come back 4 or 5 times, and the double free object appears. If I don't release any object, all is working and Instruments says that there are no memory leaks ... So, the final question, should I release those objects here or not ? Thanks, m.

    Read the article

  • Increase performance on iphone at pdf rendering

    - by burki
    Hi! I have a UITableView, and in every cell there's displayed a UIImage created from a pdf. But now the performance is very bad. Here's my code I use to generate the UIImage from the PDF. Creating CGPDFDocumentRef and UIImageView (in cellForRowAtIndexPath method): ... CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), (CFStringRef)formula.icon, NULL, NULL); CGPDFDocumentRef documentRef = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL); CFRelease(pdfURL); UIImageView *imageView = [[UIImageView alloc] initWithImage:[self imageFromPDFWithDocumentRef:documentRef]]; ... Generate UIImage: - (UIImage *)imageFromPDFWithDocumentRef:(CGPDFDocumentRef)documentRef { CGPDFPageRef pageRef = CGPDFDocumentGetPage(documentRef, 1); CGRect pageRect = CGPDFPageGetBoxRect(pageRef, kCGPDFCropBox); UIGraphicsBeginImageContext(pageRect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, CGRectGetMinX(pageRect),CGRectGetMaxY(pageRect)); CGContextScaleCTM(context, 1, -1); CGContextTranslateCTM(context, -(pageRect.origin.x), -(pageRect.origin.y)); CGContextDrawPDFPage(context, pageRef); UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return finalImage; } What can I do to increas the speed and keep the memory low?

    Read the article

  • What's a good way to remove all of the subviews of a UIScrollView?

    - by Moshe
    I have a scroll view and I need to reload the contents often while my app is running. Right now, I'm using the following line of code to remove the subviews before adding them back again: [scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; Should I be using the following instead? scrollView.subviews = nil; For some reason, the (first) above line of code seems to crash the app every 16 times it is run. Am I leaking memory somewhere? The following method takes an array of views, the scroller (which is a constant) and the direction. Edit: - (void)loadViews:(NSArray *)views IntoScroller:(UIScrollView *)scroller withDirection:(NSString *)direction{ //Set up the scrollView [scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; if([direction isEqualToString:@"horizontal"]){ scrollView.frame = CGRectMake(0, 0, 1024, 768); scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [[NSNumber numberWithUnsignedInt:[views count]] floatValue], scrollView.frame.size.height); }else if([direction isEqualToString:@"vertical"]){ scrollView.frame = CGRectMake(0, 0, 1024, 768); scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height * [[NSNumber numberWithUnsignedInt:[views count]] floatValue]); } for (int i=0; i<[[NSNumber numberWithUnsignedInt:[views count]] intValue]; i++) { [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:scrollView.frame]; if([direction isEqualToString:@"horizontal"]){ [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];//CGRectMake(i * announcementView.view.frame.size.width, -scrollView.frame.origin.x, scrollView.frame.size.width, scrollView.frame.size.height)]; }else if([direction isEqualToString:@"vertical"]){ [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(0, i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height)]; } [scrollView addSubview:[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view]]; } }

    Read the article

  • Python Django Global Variables

    - by Joe J
    Hi all, I'm looking for simple but recommended way in Django to store a variable in memory only. When Apache restarts or the Django development server restarts, the variable is reset back to 0. More specifically, I want to count how many times a particular action takes place on each model instance (database record), but for performance reasons, I don't want to store these counts in the database. I don't care if the counts disappear after a server restart. But as long as the server is up, I want these counts to be consistent between the Django shell and the web interface, and I want to be able to return how many times the action has taken place on each model instance. I don't want the variables to be associated with a user or session because I might want to return these counts without being logged in (and I want the counts to be consistent no matter what user is logged in). Am I describing a global variable? If so, how do I use one in Django? I've noticed the files like the urls.py, settings.py and models.py seems to be parsed only once per server startup (by contrast to the views.py which seems to be parsed eache time a request is made). Does this mean I should declare my variables in one of those files? Or should I store it in a model attribute somehow (as long as it sticks around for as long as the server is running)? This is probably an easy question, but I'm just not sure how it's done in Django. Any comments or advice is much appreciated. Thanks, Joe

    Read the article

  • Atomic Instructions and Variable Update visibility

    - by dsimcha
    On most common platforms (the most important being x86; I understand that some platforms have extremely difficult memory models that provide almost no guarantees useful for multithreading, but I don't care about rare counter-examples), is the following code safe? Thread 1: someVariable = doStuff(); atomicSet(stuffDoneFlag, 1); Thread 2: while(!atomicRead(stuffDoneFlag)) {} // Wait for stuffDoneFlag to be set. doMoreStuff(someVariable); Assuming standard, reasonable implementations of atomic ops: Is Thread 1's assignment to someVariable guaranteed to complete before atomicSet() is called? Is Thread 2 guaranteed to see the assignment to someVariable before calling doMoreStuff() provided it reads stuffDoneFlag atomically? Edits: The implementation of atomic ops I'm using contains the x86 LOCK instruction in each operation, if that helps. Assume stuffDoneFlag is properly cleared somehow. How isn't important. This is a very simplified example. I created it this way so that you wouldn't have to understand the whole context of the problem to answer it. I know it's not efficient.

    Read the article

  • sqlite3 - stringWithUTF8String is leaking!

    - by Darko Hebrang
    I would appreciate if someone could help me solve my leaking problem. The leaks occur at: aImage, aCategory, aDescription, category and categories. I release them in dealloc, but obviously that is not sufficient: -(void) readListFromDatabase:(char *) sqlStatement { // Setup some globals databaseName = @"mydatabase.sql"; // Get the path to the documents directory and append the databaseName NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; // Setup the database object sqlite3 *database; // Init the categories Array categories = [[NSMutableArray alloc] init]; // Open the database from the users filessytem if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) { // Setup the SQL Statement and compile it for faster access sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { // Loop through the results and add them to the feeds array while(sqlite3_step(compiledStatement) == SQLITE_ROW) { // Read the data from the result row aImage = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)]; aCategory = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; // Create a new category object with the data from the database category=[[Category alloc] initWithName:aImage category_name:aCategory description_text:aDescription]; // Add the category object to the categories Array [categories addObject:category]; [category release]; } } // Release the compiled statement from memory sqlite3_finalize(compiledStatement); } sqlite3_close(database); } - (void)dealloc { [databaseName release]; [databasePath release]; [categories release]; [aImage release]; [aCategory release]; [aDescription release]; [category release]; [super dealloc]; }

    Read the article

  • nedmalloc: where does mem<fm come from?

    - by Suma
    While implementing nedmalloc into my application, I am frequently hitting a situation when nedmalloc refuses to free a block of memory, claiming it did not allocate it. While debugging I have come up to the point I see a particular condition which is failing, all other (including magic numbers) succeed. The condition is this: if((size_t)mem-(size_t)fm>=(size_t)1<<(SIZE_T_BITSIZE-1)) return 0; On Win32 this seems to be equivalent to: if((int)((size_t)mem-(size_t)fm)<0) return 0; Which seems to be the same as: if((size_t)mem<(size_t)fm) return 0; In my case I really see mem < fm. What I do not understand now is, where does this condition come from. I cannot find anything which would guarantee the fm <= m anywhere in code. Yet, "select isn't broken": I doubt it would really be a bug in nedmalloc, most likely I am doing something wrong somewhere, but I cannot find it. Once I turn debugging features of nedmalloc on, the problem goes away. If someone here understands inner working of nedmalloc, could you please explain to me why is fm <= m?

    Read the article

  • Signal "0" error while scrolling a tableview with images

    - by Amitkumar
    Hi, I have a problem while scrolling images on tableview. I am getting a Signal "0" error. I think it is due to some memory issues but I am not able to find out the exact error. The code is as follows, - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [travelSummeryPhotosTable dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease]; } //Photo ImageView UIImageView *photoTag = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, 5.0, 85.0, 85.0)]; NSString *rowPath =[[imagePathsDictionary valueForKey:[summaryTableViewDataArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]; photoTag.image = [UIImage imageWithContentsOfFile:rowPath]; [cell.contentView addSubview:photoTag]; [photoTag release]; // Image Caption UILabel *labelImageCaption = [[UILabel alloc] initWithFrame:CGRectMake(110.0, 15.0, 190.0, 50.0)]; labelImageCaption.textAlignment = UITextAlignmentLeft; NSString *imageCaptionText =[ [imageCaptionsDictionary valueForKey:[summaryTableViewDataArray objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row]; labelImageCaption.text = imageCaptionText; [cell.contentView addSubview:labelImageCaption]; [labelImageCaption release]; return cell; } Thanks in advance.

    Read the article

< Previous Page | 122 123 124 125 126 127 128 129 130 131 132 133  | Next Page >