Static dynamic memory: oxymoronic or just plain moronic?

General discussion about C/C++

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

Static dynamic memory: oxymoronic or just plain moronic?

Postby DannyBoy » Tue May 29, 2012 7:20 am

Is it possible to perform a static dynamic memory allocation? My problem is that I need to create a static array, but that I don't know a priori the size of that array. So, for example, does the following code make any sense whatsoever:

Code: Select all
static double *C=new double[N_CELLS];


Is there a better alternative? How do I go about deallocating the memory? Would a static smart pointer make more sense? As always, any advice, comments, or mocking of my ignorance is welcome.
User avatar
DannyBoy
 
Posts: 1160
Joined: Fri Feb 13, 2004 12:56 pm
Location: In the Billiard Room with the Lead Pipe

Re: Static dynamic memory: oxymoronic or just plain moronic?

Postby exomo » Tue May 29, 2012 3:16 pm

Whether or not this makes sense depends on the place where you want to put this code and the time you know N_CELLS.
I would prefer to not use static variables with dynamically allocated memory because you don't know when to free the memory, but you could do this if you don't want to ever free the memory. I'm not sure if smart pointers would help you here.

You could just make C a global variable (or a static class member) and make an initialization and deallocation function. Call the initialization as soon as you know the value of N_CELLS and call the deallocation somewhere at the end of the main function. If you have a possibility to do it without globals or statics it would be even better, but sometimes it's not possible.
Who needs a signature anyway.
User avatar
exomo
 
Posts: 881
Joined: Fri Sep 26, 2003 12:30 pm
Location: germany->baden

Re: Static dynamic memory: oxymoronic or just plain moronic?

Postby DannyBoy » Tue May 29, 2012 3:35 pm

Thanks for your thoughts, exomo! What I ended up doing was declaring a static vector, which seems to have done the trick.
User avatar
DannyBoy
 
Posts: 1160
Joined: Fri Feb 13, 2004 12:56 pm
Location: In the Billiard Room with the Lead Pipe


Return to General

Who is online

Users browsing this forum: No registered users and 2 guests