Jump to content
  • Advertisement
Sign in to follow this  
levjs

Freeing Space: Arrays

This topic is 4886 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I am wondering, at the end of my programs how do i free up the memory used for arrays. Also, can you do the same for variables? Thanks Levi

Share this post


Link to post
Share on other sites
Advertisement
C++, i've tried using delete, but if i understand correctly, it is only used for things initialized using new, and i don't know what else to try.

Share this post


Link to post
Share on other sites

// Create a array containing 10 integers
int * int_array = new int[10];
// Cleanup
delete [] int_array;

class CObject {
private:
char * m_lpszName;
public:
CObject(char* lpszName)
{
m_lpszName;
};
virtual ~CObject() {};
};

// Allocate memory for a CObject and then call constructor
CObject * pObjectA = new CObject("Bastard");
delete pObjectA;
// Allocate memory for 32 CObjects
CObject * pObjectB = new CObject[32];
delete [] pObjectB;





Share this post


Link to post
Share on other sites
Guest Anonymous Poster
how do you allocate them?
'delete varname' goes with 'new varname'
'delete {] varname' goes with 'new varname[number]'
free goes with malloc, alloc, calloc

Share this post


Link to post
Share on other sites
If you allocate an array using new[], you free it using delete[], as follows:

int* array = new int[50];
delete[] array;


If you are not using the new keyword to create your arrays, their scope is controlled by the language. You don't have to do anything to deallocate them, they will be freed automatically when they go out of scope. If the array is declared local to a function, as follows:

void Foo()
{
int array[50];
}


The array will be freed automatically when Foo returns. If the array is declared globally, outside any function, as follows:

int array[50]

int main()
{
return 0;
}


The memory will be released when the program terminates. While in Windows, memory allocated with new will be freed when your pogram terminates too, it is not guaranteed on all platforms. You should always delete every block of memory you allocate using new at some point during your program execution. Any other variables you declare without using the new keyword, you don't have to worry about.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!