Search Results

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

Page 130/491 | < Previous Page | 126 127 128 129 130 131 132 133 134 135 136 137  | Next Page >

  • Cloned Cached item has memory issues

    - by ioWint
    Hi there, we are having values stored in Cache-Enterprise library Caching Block. The accessors of the cached item, which is a List, modify the values. We didnt want the Cached Items to get affected. Hence first we returned a new List(IEnumerator of the CachedItem) This made sure accessors adding and removing items had little effect on the original Cached item. But we found, all the instances of the List we returned to accessors were ALIVE! Object relational Graph showed a relationship between this list and the EnterpriseLibrary.CacheItem. So we changed the return to be a newly cloned List. For this we used a LINQ say (from item in Data select new DataClass(item) ).ToList() even when you do as above, the ORG shows there is a relationship between this list and the CacheItem. Cant we do anything to create a CLONE of the List item which is present in the Enterprise library cache, which DOESNT have ANY relationship with CACHE?!

    Read the article

  • Java Memory Management

    - by Tara Singh
    I am designing a client-server chat application in Java. This is a secure application where the messages are exchanged using cryptographic algorithms. I have one server and it can support many clients. My problem is that when one client logs on the server it works fine, but when another user logs into the system, the server starts giving me bad padding exceptions for the encrypted text. I am not able to figure out the problem, according to my logic, when new connection request to server is made, the server creates a thread for listening to the client. Is it possible that once the instance of thread class is created, it does all the processing correctly for the first client, but not for the second client because the variables in server listener thread class already have some previous value, and thus the encrypted text is not decrypted properly? Please advise how I can make this process more robust so that the number of clients does not affect how well the server functions.

    Read the article

  • How to access Memory pool mbeans

    - by nandula-shankar
    Hi, I want to access MemoryPool Mbeans through a java program so that I can retrieve the Eden Space, Perm Gen space, CodeCahe, Survior Space statistics during a period of time. How to do this? I tried java.lang:type=MemoryPool,name=Eden Space I wan not lucky Thanks, Shankar

    Read the article

  • Strange problem with NSMutableArray - Possibly some memory corruption

    - by user210504
    Hi! I am trying to update data in a table view using a NSMutableArray. Quite simple :( What is happening is that I get my data from a NSURLConnection Callback, which I parse and store it in an array and call reload data on the table view. The problem is that when cellForRowAtIndexPath is called back by the framework. The array still shows the correct count of the elements but all string objects I had stored earlier are shown as invalid. Any pointers

    Read the article

  • .NET JIT Code Cache leaking?

    - by pitchfork
    We have a server component written in .Net 3.5. It runs as service on a Windows Server 2008 Standard Edition. It works great but after some time (days) we notice massive slowdowns and an increased working set. We expected some kind of memory leak and used WinDBG/SOS to analyze dumps of the process. Unfortunately the GC Heap doesn’t show any leak but we noticed that the JIT code heap has grown from 8MB after the start to more than 1GB after a few days. We don’t use any dynamic code generation techniques by our own. We use Linq2SQL which is known for dynamic code generation but we don’t know if it can cause such a problem. The main question is if there is any technique to analyze the dump and check where all this Host Code Heap blocks that are shown in the WinDBG dumps come from? [Update] In the mean time we did some more analysis and had Linq2SQL as probable suspect, especially since we do not use precompiled queries. The following example program creates exactly the same behaviour where more and more Host Code Heap blocks are created over time. using System; using System.Linq; using System.Threading; namespace LinqStressTest { class Program { static void Main(string[] args) { for (int i = 0; i < 100; ++ i) ThreadPool.QueueUserWorkItem(Worker); while(runs < 1000000) { Thread.Sleep(5000); } } static void Worker(object state) { for (int i = 0; i < 50; ++i) { using (var ctx = new DataClasses1DataContext()) { long id = rnd.Next(); var x = ctx.AccountNucleusInfos.Where(an => an.Account.SimPlayers.First().Id == id).SingleOrDefault(); } } var localruns = Interlocked.Add(ref runs, 1); System.Console.WriteLine("Action: " + localruns); ThreadPool.QueueUserWorkItem(Worker); } static Random rnd = new Random(); static long runs = 0; } } When we replace the Linq query with a precompiled one, the problem seems to disappear.

    Read the article

  • memory alignment within gcc structs

    - by Mumbles
    I am porting an application to an ARM platform in C, the application also runs on an x86 processor, and must be backward compatible. I am now having some issues with variable alignment. I have read the gcc manual for __attribute__((aligned(4),packed)) I interpret what is being said as the start of the struct is aligned to the 4 byte boundry and the inside remains untouched because of the packed statement. originally I had this but occasionally it gets placed unaligned with the 4 byte boundary. typedef struct { unsigned int code; unsigned int length; unsigned int seq; unsigned int request; unsigned char nonce[16]; unsigned short crc; } __attribute__((packed)) CHALLENGE; so I change it to this. typedef struct { unsigned int code; unsigned int length; unsigned int seq; unsigned int request; unsigned char nonce[16]; unsigned short crc; } __attribute__((aligned(4),packed)) CHALLENGE; The understand I stated earlier seems to be incorrect as both the struct is now aligned to a 4 byte boundary, and and the inside data is now aligned to a four byte boundary, but because of the endianess, the size of the struct has increased in size from 42 to 44 bytes. This size is critical as we have other applications that depend on the struct being 42 bytes. Could some describe to me how to perform the operation that I require. Any help is much appreciated.

    Read the article

  • Can i openly speculate based on App rejection that the iPad has xxx MB of memory?

    - by GamingHorror
    If i were to calculate the iPad's amount of RAM based on just the one fact that my iPad App got rejected due to memory warnings twice, and me fixing it, would this violate the developer NDA? Obviously i know how much memory my App uses, how much the iPhone OS is likely to use and estimate the amount reserved for video memory, then i can deduct from that that the iPad has xxx MB of memory. I just wonder if i can say that number publicly without violating any NDA?

    Read the article

  • MPMediaickerController memory leak

    - by Joe
    This is code from Apple's Addmusic example. MPMediaPickerController *picker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic]; picker.delegate = self; picker.allowsPickingMultipleItems = YES; picker.prompt = NSLocalizedString (@"Add songs to play", "Prompt in media item picker"); // The media item picker uses the default UI style, so it needs a default-style // status bar to match it visually [[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault animated: YES]; [self presentModalViewController: picker animated: YES]; [picker release]; I'm using this code in my app and the Leaks instrument highlights a leak on the line: [self presentModalViewController: picker animated: YES]; I think that this is because this line retains a reference to picker which cannot be subsequently released. Is there any way around this?

    Read the article

  • calling calloc - memory leak valgrind

    - by Mike
    The following code is an example from the NCURSES menu library. I'm not sure what could be wrong with the code, but valgrind reports some problems. Any ideas... ==4803== 1,049 (72 direct, 977 indirect) bytes in 1 blocks are definitely lost in loss record 25 of 36 ==4803== at 0x4C24477: calloc (vg_replace_malloc.c:418) ==4803== by 0x400E93: main (in /home/gerardoj/a.out) ==4803== ==4803== LEAK SUMMARY: ==4803== definitely lost: 72 bytes in 1 blocks ==4803== indirectly lost: 977 bytes in 10 blocks ==4803== possibly lost: 0 bytes in 0 blocks ==4803== still reachable: 64,942 bytes in 262 blocks Source code: #include <curses.h> #include <menu.h> #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) #define CTRLD 4 char *choices[] = { "Choice 1", "Choice 2", "Choice 3", "Choice 4", "Choice 5", "Choice 6", "Choice 7", "Exit", } ; int main() { ITEM **my_items; int c; MENU *my_menu; int n_choices, i; ITEM *cur_item; /* Initialize curses */ initscr(); cbreak(); noecho(); keypad(stdscr, TRUE); /* Initialize items */ n_choices = ARRAY_SIZE(choices); my_items = (ITEM **)calloc(n_choices + 1, sizeof(ITEM *)); for (i = 0; i < n_choices; ++i) { my_items[i] = new_item(choices[i], choices[i]); } my_items[n_choices] = (ITEM *)NULL; my_menu = new_menu((ITEM **)my_items); /* Make the menu multi valued */ menu_opts_off(my_menu, O_ONEVALUE); mvprintw(LINES - 3, 0, "Use <SPACE> to select or unselect an item."); mvprintw(LINES - 2, 0, "<ENTER> to see presently selected items(F1 to Exit)"); post_menu(my_menu); refresh(); while ((c = getch()) != KEY_F(1)) { switch (c) { case KEY_DOWN: menu_driver(my_menu, REQ_DOWN_ITEM); break; case KEY_UP: menu_driver(my_menu, REQ_UP_ITEM); break; case ' ': menu_driver(my_menu, REQ_TOGGLE_ITEM); break; case 10: { char temp[200]; ITEM **items; items = menu_items(my_menu); temp[0] = '\0'; for (i = 0; i < item_count(my_menu); ++i) if(item_value(items[i]) == TRUE) { strcat(temp, item_name(items[i])); strcat(temp, " "); } move(20, 0); clrtoeol(); mvprintw(20, 0, temp); refresh(); } break; } } free_item(my_items[0]); free_item(my_items[1]); free_menu(my_menu); endwin(); }

    Read the article

  • Read variable-length records from a buffer - weird memory issues

    - by bsg
    Hi, I'm trying to implement an i/o intensive quicksort (C++ qsort) on a very large dataset. In the interests of speed, I'd like to read in a chunk of data at a time into a buffer and then use qsort to sort it inside the buffer. (I am currently working with text files but would like to move to binary soon.) However, my data is composed of variable-length records, and qsort needs to be told the length of the record in order to sort. Is there any way to standardize this? The only thing I could think of was rather convoluted: my program currently reads from the buffer until it hits a linefeed character ('10' in ascii), transferring each character over to another array. When it finds a linefeed (the delimiter in the input file), it fills the number of spaces remaining in the buffer for that record (record size is set to 30) with null characters. This way, I should end up with a buffer full of fixed-size records to give qsort. I know there are several problems with my approach, one being that it's just clumsy, another that the record size might conceivably be larger than 30, but is generally much less. Is there a better way of doing this? As well, my current code doesn't even work. When I debug it, it seems to be transferring characters from one buffer to the other, but when I try to print out the buffer, it contains only the first record. Here is my code: FILE *fp; unsigned char *buff; unsigned char *realbuff; FILE *inputFiles[NUM_INPUT_FILES]; buff = (unsigned char *) malloc(2048); realbuff = (unsigned char *) malloc(NUM_RECORDS * RECORD_SIZE); fp = fopen("postings0.txt", "r"); if(fp) { fread(buff, 1, 2048, fp); /*for(int i=0; i <30; i++) cout << buff[i] <<endl;*/ int y=0; int recordcounter = 0; //cout << buff; for(int i=0;i <100; i++) { if(buff[i] != char(10)) { realbuff[y] = buff[i]; y++; recordcounter++; } else { if(recordcounter < RECORD_SIZE) for(int j=recordcounter; j < RECORD_SIZE;j++) { realbuff[y] = char(0); y++; } recordcounter = 0; } } cout << realbuff <<endl; cout << buff; } else cout << "sorry"; Thank you very much, bsg

    Read the article

  • Wondering about a way to conserve memory in C# using List<> with structs

    - by Michael Ryan
    I'm not even sure how I should phrase this question. I'm passing some CustomStruct objects as parameters to a class method, and storing them in a List. What I'm wondering is if it's possible and more efficient to add multiple references to a particular instance of a CustomStruct if a equivalent instance it found. This is a dummy/example struct: public struct CustomStruct { readonly int _x; readonly int _y; readonly int _w; readonly int _h; readonly Enum _e; } Using the below method, you can pass one, two, or three CustomStruct objects as parameters. In the final method (that takes three parameters), it may be the case that the 3rd and possibly the 2nd will have the same value as the first. List<CustomStruct> _list; public void AddBackground(CustomStruct normal) { AddBackground(normal, normal, normal); } public void AddBackground(CustomStruct normal, CustomStruct hover) { AddBackground(normal, hover, hover); } public void AddBackground(CustomStruct normal, CustomStruct hover, CustomStruct active) { _list = new List<CustomStruct>(3); _list.Add(normal); _list.Add(hover); _list.Add(active); } As the method stands now, I believe it will create new instances of CustomStruct objects, and then adds a reference of each to the List. It is my understanding that if I instead check for equality between normal and hover and (if equal) insert normal again in place of hover, when the method completes, hover will lose all references and eventually be garbage collected, whereas normal will have two references in the List. The same could be done for active. That would be better, right? The CustomStruct is a ValueType, and therefore one instance would remain on the Stack, and the three List references would just point to it. The overall List size is determined not by the object Type is contains, but by its Capacity. By eliminating the "duplicate" CustomStuct objects, you allow them to be cleaned up. When the CustomStruct objects are passed to these methods, new instances are created each time. When the structs are added to the List, is another copy made? For example, if i pass just one CustomStruct, AddBackground(normal) creates a copy of the original variable, and then passes it three times to Addbackground(normal, hover, active). In this method, three copies are made of the original copy. When the three local variables are added to the List using Add(), are additional copies created inside Add(), and does that defeat the purpose of any equality checks as previously mentioned? Am I missing anything here?

    Read the article

  • Update count every second causing massive memory problems

    - by Josh
    Just on my local machine, trying the run the following script causes my computer to crash... What am I doing wrong? (function($) { var count = '6824756980'; while (count > 0) { setInterval(function() { $('#showcount').html(Math.floor(count-1)); count--; }, 1000 ); } })(jQuery); All I need to do is subtract one from the var "count" and update/display it's value every second.

    Read the article

  • objective c - memory managment

    - by Amir
    lets say I have aclass @interface Foo :NSobject { NSstring *a; NSDate *b; } Foo *temp; my question is: when i use [temp retain] does the counter of the members also retain? lets say that i got ref of the class from some method and i want to retain the class do i need to retain each member?

    Read the article

  • Eidetic memory: What magic numbers you still remember?

    - by Hao
    Long before you practice writing readable code, what "magic numbers" you still remember up to this day? here's some of my list: 72 80 75 77 13 32 27 - up down left right enter space escape 1 2 4 128 - blue green red blink 67h 33h 17h - interrupt for EMS, mouse, printer function AH 9, interrupt 21 alt+219 for block ASCII alt+164 ñ 90 NOP 13 10 carriage return, line feed ascii 1 and 2 face, ascii 3 heart. no not this heart: <3 :-) debug -o72,10 -o71,12 clears the BIOS password. I don't know what those numbers mean, it's like a trade secret that gets shared with each other during college days. ascii 7 sounds a beep P.S. Somehow, remembering some of these magic numbers can help you in some tech problems, your keyboard is broken, the office pal's keyboard doesn't have accented characters. An anecdote, during college, one of my friend asked me how to remove the newlines in his Word document. Not having used Word so much then, I somehow "intuitively" guessed to find ^013 and replace it with blank. Well it works :-)

    Read the article

  • Loading a page into memory in Rails

    - by titaniumdecoy
    My rails app produces XML when I load /reports/generate_report.xml. On a separate page, I want to read this XML into a variable and save it to the database. How can I do this? Can I somehow stream the response from the /reports/generate_report.xml URI into a variable? Or is there a better way to do it since the XML is produced by the same web app?

    Read the article

  • Sending an email attachment in memory using OpenXML

    - by ohnoesitsbroken
    I've got an Excel file that's built using OpenXML 2 and I want to send it as an email attachment. e.g. System.IO.MemoryStream stream = new System.IO.MemoryStream(); SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook)) AddParts(package); //created using document reflector Saving the spreadsheet to a temp file using stream.WriteTo(new System.IO.FileStream(@"c:\test.xlsx", System.IO.FileMode.Create)); works fine. But trying to send the stream directly as an email attachment fails - just get an empty file attached to the email when I do System.Net.Mail.Attachment file = new System.Net.Mail.Attachment(stream, "MobileBill.xlsx", "application/vnd.ms-excel"); Anbody know how to do this?

    Read the article

  • EXC_BAD_ACCESS when I change moviePlayer contentURL

    - by Bruno
    Hello, In few words, my application is doing that : 1) My main view (MovieListController) has some video thumbnails and when I tap on one, it displays the moviePlayer (MoviePlayerViewController) : MovieListController.h : @interface MoviePlayerViewController : UIViewController <UITableViewDelegate>{ UIView *viewForMovie; MPMoviePlayerController *player; } @property (nonatomic, retain) IBOutlet UIView *viewForMovie; @property (nonatomic, retain) MPMoviePlayerController *player; - (NSURL *)movieURL; @end MovieListController.m : MoviePlayerViewController *controllerTV = [[MoviePlayerViewController alloc] initWithNibName:@"MoviePlayerViewController" bundle:nil]; controllerTV.delegate = self; controllerTV.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; [self presentModalViewController: controllerTV animated: YES]; [controllerTV release]; 2) In my moviePlayer, I initialize the video I want to play MoviePlayerViewController.m : @implementation MoviePlayerViewController @synthesize player; @synthesize viewForMovie; - (void)viewDidLoad { NSLog(@"start"); [super viewDidLoad]; self.player = [[MPMoviePlayerController alloc] init]; self.player.view.frame = self.viewForMovie.bounds; self.player.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [self.viewForMovie addSubview:player.view]; self.player.contentURL = [self movieURL]; } - (void)dealloc { NSLog(@"dealloc TV"); [player release]; [viewForMovie release]; [super dealloc]; } -(NSURL *)movieURL { NSBundle *bundle = [NSBundle mainBundle]; NSString *moviePath = [bundle pathForResource:@"FR_Tribord_Surf camp_100204" ofType:@"mp4"]; if (moviePath) { return [NSURL fileURLWithPath:moviePath]; } else { return nil; } } - It's working good, my movie is display My problem : When I go back to my main view : - (void) returnToMap: (MoviePlayerViewController *) controller { [self dismissModalViewControllerAnimated: YES]; } And I tap in a thumbnail to display again the moviePlayer (MoviePlayerViewController), I get a *Program received signal: “EXC_BAD_ACCESS”.* In my debugger I saw that it's stopping on the thread "main" : // // main.m // MoviePlayer // // Created by Eric Freeman on 3/27/10. // Copyright Apple Inc 2010. All rights reserved. // #import <UIKit/UIKit.h> int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); //EXC_BAD_ACCESS [pool release]; return retVal; } If I comment self.player.contentURL = [self movieURL]; it's working, but when I let it, iI have this problem. I read that it's due to null pointer or memory problem but I don't understand why it's working the first time and not the second time. I release my object in dealloc method. Thanks for your help ! Bruno.

    Read the article

  • iPhone: Problems releasing UIViewController in a multithreaded environment

    - by bart-simpson
    Hi! I have a UIViewController and in that controller, i am fetching an image from a URL source. The image is fetched in a separate thread after which the user-interface is updated on the main thread. This controller is displayed as a page in a UIScrollView parent which is implemented to release controllers that are not in view anymore. When the thread finishes fetching content before the UIViewController is released, everything works fine - but when the user scrolls to another page before the thread finishes, the controller is released and the only handle to the controller is owned by the thread making releaseCount of the controller equals to 1. Now, as soon as the thread drains NSAutoreleasePool, the controller gets releases because the releaseCount becomes 0. At this point, my application crashes and i get the following error message: bool _WebTryThreadLock(bool), 0x4d99c60: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... The backtrace reveals that the application crashed on the call to [super dealloc] and it makes total sense because the dealloc function must have been triggered by the thread when the pool was drained. My question is, how i can overcome this error and release the controller without leaking memory? One solution that i tried was to call [self retain] before the pool is drained so that retainCount doesn't fall to zero and then using the following code to release controller in the main thread: [self performSelectorOnMainThread:@selector(autorelease) withObject:nil waitUntilDone:NO]; Unfortunately, this did not work out. Below is the function that is executed on a thread: - (void)thread_fetchContent { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSURL *imgURL = [NSURL URLWithString:@"http://www.domain.com/image.png"]; // UIImage *imgHotspot is declared as private - The image is retained // here and released as soon as it is assigned to UIImageView imgHotspot = [[[UIImage alloc] initWithData: [NSData dataWithContentsOfURL: imgURL]] retain]; if ([self retainCount] == 1) { [self retain]; // increment retain count ~ workaround [pool drain]; // drain pool // this doesn't work - i get the same error [self performSelectorOnMainThread:@selector(autorelease) withObject:nil waitUntilDone:NO]; } else { // show fetched image on the main thread - this works fine! [self performSelectorOnMainThread:@selector(showImage) withObject:nil waitUntilDone:NO]; [pool drain]; } } Please help! Thank you in advance.

    Read the article

  • how to handle out of memory error?

    - by UMMA
    dear friends, i am using following code to display bitmap in my imageview. when i try to load image of size for example bigger than 1.5MB it give me error any one suggest me solution? try { URL aURL = new URL(myRemoteImages[val]); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = null; try { is= conn.getInputStream(); }catch(IOException e) { return 0; } int a= conn.getConnectTimeout(); BufferedInputStream bis = new BufferedInputStream(is); Bitmap bm; try { bm = BitmapFactory.decodeStream(bis); }catch(Exception ex) { bis.close(); is.close(); return 0; } bis.close(); is.close(); img.setImageBitmap(bm); } catch (IOException e) { return 0; } return 1; Log cat 06-14 12:03:11.701: ERROR/AndroidRuntime(443): Uncaught handler: thread main exiting due to uncaught exception 06-14 12:03:11.861: ERROR/AndroidRuntime(443): java.lang.OutOfMemoryError: bitmap size exceeds VM budget 06-14 12:03:11.861: ERROR/AndroidRuntime(443): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)

    Read the article

  • Serialize Forms into memory

    - by serhio
    Background: In a desktop MDI application we have a lot of forms. Task: Save the controls contents of closed forms(textbox texts, checkbox checks etc). Limitations: A saved form for (DB/Windows) user? For (DB/Windows) group of users? Both variants may be possible. Question: a) What is the best way? b) if I want do not use files, how to serialize the form into a MemoryStream and then recuperate it if the opening form was been once opened and serialized? StartingPoint: Implemented a form that implements ISerializable. Deserialize the form on opening, serialize onclosing: Public Sub GetObjectData(ByVal info As System.Runtime.Serialization.SerializationInfo, ByVal context As System.Runtime.Serialization.StreamingContext) Implements System.Runtime.Serialization.ISerializable.GetObjectData info.AddValue("tbxExportFolder", tbxExportFolder.Text, GetType(String)) info.AddValue("cbxCheckAliasUnicity", cbxCheckAliasUnicity.Checked, GetType(Boolean)) End Sub Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) Me.New() Me.tbxExportFolder.Text = info.GetString("tbxExportFolder") Me.cbxCheckAliasUnicity.Checked = info.GetBoolean("cbxCheckAliasUnicity") End Sub Private Sub SerializeMe() Dim binFormatter As New Formatters.Binary.BinaryFormatter Dim fileStream As New FileStream(SerializedFilename, FileMode.Create) Try binFormatter.Serialize(fileStream, Me) Catch Throw Finally fileStream.Close() End Try End Sub Protected Overrides Sub OnClosing(ByVal e As System.ComponentModel.CancelEventArgs) SerializeMe() MyBase.OnClosing(e) End Sub

    Read the article

  • Getting memory allocation in segement control

    - by Rani
    Hi guys, I'm getting object allocation at segement control.I used same controller for adding favourites and while in didselect action.In present modelviewcontrol i didn't use segment control and in didselect i used segemnt control .So, am not getting how to release segemnt control . Can any one help to solve this. Thanks in advance.

    Read the article

  • Unique_ptr compiler errors

    - by Godric Seer
    I am designing and entity-component system for a project, and C++ memory management is giving me a few issues. I just want to make sure my design is legitimate. So to start I have an Entity class which stores a vector of Components: class Entity { private: std::vector<std::unique_ptr<Component> > components; public: Entity() { }; void AddComponent(Component* component) { this -> components.push_back(std::unique_ptr<Component>(component)); } ~Entity(); }; Which if I am not mistaken means that when the destructor is called (even the default, compiler created one), the destructor for the Entity, will call ~components, which will call ~std::unique_ptr for each element in the vector, and lead to the destruction of each Component, which is what I want. The component class has virtual methods, but the important part is its constructor: Component::Component(Entity parent) { parent.addComponent(this) // I am not sure if this would work like I expect // Other things here } As long as passing this to the method works, this also does what I want. My confusion is in the factory. What I want to do is something along the lines of: std::shared_ptr<Entity> createEntity() { std::shared_ptr<Entity> entityPtr(new Entity()); new Component(*parent); // Initialize more, and other types of Components return entityPtr; } Now, I believe that this setup will leave the ownership of the Component in the hands of its Parent Entity, which is what I want. First a small question, do I need to pass the entity into the Component constructor by reference or pointer or something? If I understand C++, it would pass by value, which means it gets copied, and the copied entity would die at the end of the constructor. The second, and main question is that code based on this sample will not compile. The complete error is too large to print here, however I think I know somewhat of what is going on. The compiler's error says I can't delete an incomplete type. My Component class has a purely virtual destructor with an implementation: inline Component::~Component() { }; at the end of the header. However since the whole point is that Component is actually an interface. I know from here that a complete type is required for unique_ptr destruction. The question is, how do I work around this? For reference I am using gcc 4.4.6.

    Read the article

  • linked list elements gone?

    - by Hristo
    I create a linked list dynamically and initialize the first node in main(), and I add to the list every time I spawn a worker process. Before the worker process exits, I print the list. Also, I print the list inside my sigchld signal handler. in main(): head = NULL; tail = NULL; // linked list to keep track of worker process dll_node_t *node; node = (dll_node_t *) malloc(sizeof(dll_node_t)); // initialize list, allocate memory append_node(node); node->pid = mainPID; // the first node is the MAIN process node->type = MAIN; in a fork()'d process: // add to list dll_node_t *node; node = (dll_node_t *) malloc(sizeof(dll_node_t)); append_node(node); node->pid = mmapFileWorkerStats->childPID; node->workerFileName = mmapFileWorkerStats->workerFileName; node->type = WORK; functions: void append_node(dll_node_t *nodeToAppend) { /* * append param node to end of list */ // if the list is empty if (head == NULL) { // create the first/head node head = nodeToAppend; nodeToAppend->prev = NULL; } else { tail->next = nodeToAppend; nodeToAppend->prev = tail; } // fix the tail to point to the new node tail = nodeToAppend; nodeToAppend->next = NULL; } finally... the signal handler: void chld_signalHandler() { dll_node_t *temp1 = head; while (temp1 != NULL) { printf("2. node's pid: %d\n", temp1->pid); temp1 = temp1->next; } int termChildPID = waitpid(-1, NULL, WNOHANG); dll_node_t *temp = head; while (temp != NULL) { if (temp->pid == termChildPID) { printf("found process: %d\n", temp->pid); } temp = temp->next; } return; } Is it true that upon the worker process exiting, the SIGCHLD signal handler is triggered? If so, that would mean that after I print the tree before exiting, the next thing I do is in the signal handler which is print the tree... which would mean i would print the tree twice? But the tree isn't the same. The node I add in the worker process doesn't exist when I print in the signal handler or at the very end of main(). Any idea why? Thanks, Hristo

    Read the article

< Previous Page | 126 127 128 129 130 131 132 133 134 135 136 137  | Next Page >