Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.


Allocating Memory in C++

This topic is 5532 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

My question is, whats the use of allocating memory in the pointers, whats with the use of new and delete, and there is stack and the heap, i''m totally confused in the pointer section, i know what pointer is and what it does, just not the allocating memory stuff and the stack and heap. thx for answering

Share this post

Link to post
Share on other sites
Well, memory is where everything on the computer is held, including all your program stuff (code, resources, graphics, etc). So you need to allocate some for your program to use.

The new and delete commands are basicly to help you make allocating memory easier.

See, new can allocate you ANY type of memory, by using the following code:

void *pointer = new dataType;

''dataType'' would be replace with whatever kind of data type you need allocated (int, char, long, etc).

Then of course, the allocated data has to be released back to the system, and that''s where delete comes in:

delete[] pointer;

So there ya go, I hope helped.

THIS book rocks.

3D gaming Haven Opening soon.

Share this post

Link to post
Share on other sites
Please ignore most of DariusX's response.

1) his use of delete is incorrect in his example. delete[] is only used for memory that was allocated as an array

2) you should never do :

void* pointer = new ....;

This destroys type safety in the worst way. Not only can you very easily forget what pointer points to (is it ints? a single char? a complicated object?), but to use the pointer in any useful way, you have to cast it to its correct type.

3) he does not address your questions about heap and stack

You can think of it this way:

- there are things in your program which you may want to allocate dynamically (i.e. at runtime) versus setting up memory beforehand.

I'll give you a simple example is: if a wizard player has spells to summon creatures, you have no idea which spell he will cast. If he casts a "summon skeleton" spell, you have to allocate memory for a skeleton creature and then put him into the game. But the player could also cast a "summon goblin army" spell, which means you'll have to allocate memory for a large number of goblins instead. You don't want to have to allocate all the memory at once in your program to cover all cases. What you need to do is:

- when the player casts the spell, allocate the memory you need
- when the creature(s) die(s), then de-allocate the memory

Hopefully this gives you a good understanding of why you need to dynamically allocate memory. To do this in C++, you use new/delete.

When you use new/delete as they are, you will be allocating memory on the heap (unless you're using more advanced techniques like your own memory manager, etc). Think of it this way: the heap is just one giant blob (or heap!) of memory that you can allocate and de-allocate to your heart's content in the program.

Now the stack: The stack is a smaller (and usually quicker!) region of memory that is used within a function to store temporary variables (i.e. variables that will be automatically de-allocated once the end of the function is reached. For example:

void goo(int x) { cout << x << endl; }
void foo() {
int v = 5; // v is placed on the stack
} // v is de-allocated from the stack here

void main() {

The variable v is allocated on the stack upon entering foo() but is de-allocated when foo() exits.

Hope this helps.


[edited by - rypyr on April 28, 2003 5:20:09 PM]

Share this post

Link to post
Share on other sites
I am not an expert, but i shall try to explain what i understand.
Added to the previous post by DariusX, whenever you use variables in your class/functions they are requests to the system for storing some data and they need to be given some place to live. The C/C++ compiler will allocate the "living" areas for the variables based on how you declare them.
e.g. if you consider the following code

void main()
int x; //Local variable
char y[20]; //Local variable

// do something here and that is it.

The x and y are called local to the function and therefore will be allocated "living" quarters in a community called "Stack". [Just a name for the memory block that holds temporary/local variables]. These variables cannot be accessed from anywhere outside the scope of the function and therefore have a short lifespan. They are volatile and "die" as soon as you get out of the function. So stuff that goes into the "Stack" lives only for a short span. One other point to note here is that for such variables, the entire amount of space required is allocated. so x will be given sizeof(int) bytes depending on system and the variable "y" will be allocated 20xsizeof(char) bytes. This space will be claimed back automatically.

Consider the following piece of code.
void main()
int *pX = NULL;
pX = new int[5];
Here during the first line [declaration] pX is not allocated any "living" quarters other than 2 Bytes for storing the address of the variable pX. You only inform the compiler that you may store any number of elements later on. So in the next line when you say new int[5], the system will create 5 entries, each capable of holding an integer and then return the address of the first element to pX. Now, this area that was just allocated should be managed by the programmer; what this means is that, you have to free up the "new"ed elements when you are done. Why? because, the "living" quarters that was just allocated for pX was done from a different community called "Heap". That is the characteristic of "new"/"malloc"/"calloc"/et al. The way to free up the allocated memory is to use "delete". When programmers forget to free up memory that they no longer use/need, or delete the wrong pointer you have all sorts of funny behaviour in the system...... and can even lead to Blue Screen of Deaths.

Hope i did not try to explain something that you already knew. If it is confusing and need more explanation, i can try to do that.

Have a good time conquering pointers!!!

Share this post

Link to post
Share on other sites
I had a delay between when i started my reply and actually posted it. I therefore, could not take into account rypyr''s response. rypyr''s response sounds even more "practical" to the kind of applications that you will be dealing with and should be more helpful. Good one rypyr.


Share this post

Link to post
Share on other sites
NewbieGamer: You''re answer was also quite good and touched a little more on how to actually use new, which I neglected.

DariusX: Sorry if I offended you, I guess I was a little harsh. However, I felt much of what you stated was either erroneous or misleading. Posting for the sake of posting (without a solid understanding of the topic) can potentially lead to disaster.

Share this post

Link to post
Share on other sites
Guest Anonymous Poster
Alrighty lets get down to the nitty gritty of it all.

In order to make any type of program (including games) you need to have memory. This is why when you purchase a new computer you get to select how much memory you want to have. This type of memory is called RAM (random access memory) and provides you a buffer of sorts when you run your program.

Every time you make a variable you use up some ram for instance:

int myInt; (on a windows 32 system this will take up 32bits of RAM)
char myChar (on a windows 32 system this will take up 8 bits of RAM).

The above are examples of "static memory". Static memory itself never changes when you hit the compile button. It''ll never take up more memory or less memory than it''s ment to (theoretically speaking. I don''t want to confuse you with alignment issues quite yet).

Now this creates a problem because often when we make applcations we don''t always know how large an array needs to be in order to fit all the data. For instance lets say you and your buddy Jim are writing papers for a class. The teacher did not say how long your papers needed to be. So the next day you come to school with a paper that''s 10 pages long while Jim comes to school with a paper that''s 1 page long. The question then becomes if you had to write a program to load the text up into a buffer and print it out on screen could you possibly know ahead of time the maximum ammount of pages everyone in your class would write? It''s impossible to know this ahead of time (unless your Miss Cleo)!

Fortunately we have an alternative to static memory and it''s called dynamic memory. This type of memory doesn''t remain constant, you can change the size of an array from 32 to 50 and then back to 10 if need be. How do we use this type of memory? new and delete of course!

But before we can use the memory we need to create a pointer to point at the memory we are about to allocate.....
int *integerArray = 0; now we can create an integer array integerArray = new int[32]; (if we were to do this statically we''d type in int integerArray[32]. So what exactly does new do? Well it goes through your memory and looks for a slot large enough to hold the array. In our case the size of an int is 4 bytes, and the number of ints we want to allocate is 32...so 4*32 = 128. So new goes looking for 128 bytes of free memory to use, when it finds a spot with enough memory available it returns the address. Now your pointer points to a spot in RAM that''s large enough to store 32 integers.

Now because we are allocating this dynamically we have to clean up our own mess before the program exits. You see the program itself knows nothing about the dynamically allocated memory it just sees a pointer to memory. So if we don''t use delete on the pointer before exiting we''ll create a "Memory Leak". A memory leak happens when you allocate a bunch of memory and never release it. It can cause your computer to slow down alot or even crash, so we want to make sure that this gets cleaned up. So before we exit our program we call "delete [] integerArray;" note that the []''s are only used when you''ve allocated an array, if you used new to allocate a single integer or character or any other singlular thing then you''d just use "delete integer;" instead.

This should''ve answerd the majority of your questions. As for the stack and heap for now you don''t need to be worried about them, progress on into your learning and you''ll be ready to tackle these another day.

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

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

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!