C++ dynamic memory allocation question (for college)

i_hate_toms

New Member
Hello everyone, hope you're doing good :)
Please take a look at the following program:-
//INDEPENDENT MODULE:dynamic memory allocation with keyword "new"
#include<iostream>
#include<conio.h>
using namespace std;
void main()
{
int *ptr; //declaring integer pointer
cout<<"Attempting dynamic memory allocation now...\n";
ptr=new int;//attempting to allocate memory for the integer using keyword new
if(!ptr)//check if allocation successful, NULL is returned if allocation fails
{
cout<<"Memory Allocation Failed!";//Message displayed if allocation failed
}
else //enter this block only if allocation has succeeded, ie,"ptr!=NULL"
{
cout<<"SUCCESS: Memory allocated for int object\n";//Display message confirming allocation
cout<<"Enter integer value ";//ask end user to enter integer value
cin>>*ptr; //accept a value and store at the memory address pointed by integer type pointer variable "*ptr"
int x=*ptr;//declare integer variable "x" and assign the user-entered value to x, using indirection
cout<<"Value "<<x<<" assigned to memory address "<<&x<<" by indirection\n"; //display result
cout<<"Press any key to exit...";//Graceful Shutdown Prompt
getch();
}
}
What's going on at "ptr=new int" ?
Why do we need to learn this weird process? Why not write
int x;
cin>>x;
???
Thnx..
 
This is just a horrible example of pointers. I imagine it's supposed to be a gentle introduction though.

new allocates memory for that type. Something slightly more interesting might be this:

Code:
int *example;

example = new int[10];

What you are doing is allocating memory from the heap instead of stack.
 
Thanks for your reply Crome :)
This is just a horrible example of pointers. I imagine it's supposed to be a gentle introduction though.
it is an introduction i guess, today was the first class on pointers :p

new allocates memory for that type. Something slightly more interesting might be this:

Code:
int *example;

example = new int[10];

What you are doing is allocating memory from the heap instead of stack.
This isn't the only program the professor showed us today, this was the "first", and there are others, including one that looks like the one you mentioned, but i thought I'd start with the first one first, cause it'd be easier to understand :P

Heap/Stack, sorry didn't understand that, can you explain a bit or maybe give me a link?
What on earth is the advantage of using this method when we can simply write "int x= (insert integer value here); ??
I'm finding it useless and unnecessarily complicating a simple task!! :confused::confused:

Thanks for your help :)
Got a test on pointers this next thursday, i'll post the questions here after i take the test, that'd be fun i guess :)
 
There's an answer on stackoverflow that covers stack vs heap in detail, it might go a bit deeper than is needed though:
http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap said:
The stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local variables and some bookkeeping data. When that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order; the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack; freeing a block from the stack is nothing more than adjusting one pointer.

The heap is memory set aside for dynamic allocation. Unlike the stack, there's no enforced pattern to the allocation and deallocation of blocks from the heap; you can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time; there are many custom heap allocators available to tune heap performance for different usage patterns.

Each thread gets a stack, while there's typically only one heap for the application (although it isn't uncommon to have multiple heaps for different types of allocation).

To answer your questions directly:



To what extent are they controlled by the OS or language runtime?

The OS allocates the stack for each system-level thread when the thread is created. Typically the OS is called by the language runtime to allocate the heap for the application.



What is their scope?

The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application (technically process) exits.



What determines the size of each of them?

The size of the stack is set when a thread is created. The size of the heap is set on application startup, but can grow as space is needed (the allocator requests more memory from the operating system).



What makes one faster?

The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free. Also, each byte in the stack tends to be reused very frequently which means it tends to be mapped to the processor's cache, making it very fast.

So now that you're thoroughly confused, the very simple version is your parameters, function callss and local variables exist on the stack. Only 1 value is accessible on the stack at a time (the last one you put there).

The heap is just a memory area where you can ask for memory. When you ask for memory in the heap it comes from *somewhere*, you don't know, but since the entire area is accessible it doesn't matter.

If the heap didn't exist you'd have to know the size of everything before hand. This is the advantage to using new instead of int abc[10].
 
thanls again crome :)
ok so what you're suggesting is, if i know how much space is required for some variable, i can directly declare it, like int a; float b; char c[50]; etc..
but if i don't know how much memory space is required, i have to use this method, right?
If that's right, can you give me a real-life example where i don't know how much memory would be required to represent something?
i mean, in every case i can think of, the space required is already known at program time, like int will always use x bytes, float will always use y bytes, etc.;
Maybe you can write some function here and show a situation where we are not aware of how much memory is required?
Thanks thanks thanks :) :good:
To be honest, this still looks like a complicated process, doesn't it? :P
PS: Thanks for the stack/heap link :)
 
Say you are reading a database and you've created an object which exactly matches a row in your table. Instead of making a big array of objects or selecting the count out, you can just say while (more records) new object. Or when reading user input. The C++ String type uses dynamic memory to store what you stick in it.

The trouble with learning about pointers is the initial stuff they show you are generally bad examples.
 
Man, dbms used to be one of my fav subjects in high school, they made us work with MS Access back then.
Now in college, we yet again have dbms, and it's starting to become a real pain.
The difference is, now we are not allowed to use access.
Instead we have a thing called "Oracle 9i".
The professors think it's better, I'm finding it stupid duhh.
It doesn't seem to have a proper GUI. I open it, i get this white screen asking "Username", "password", and "host string".
I fill this up (Prof has given each one us a unique ID, we chose the pwd, and "host string" is common for all, it's the name of the university), i get a white screen with a DOS-like command prompt that says "SQL > "
And then we have to write these weird commands here, (ex:- ed filename,
@ filename, etc).
How is this better than Microsoft Access? Duhh.
But thanks for the pointers help bro, yea the examples they have shown aren't really that good. The alternative "no pointers" straightforward approach looks better. Maybe I'll get to appreciate pointers when i learn more about them. Thanks :)
 
I actually like Oracle, it's way better than Access. No corruption once your database hits a certain size and it has a GUI frontend option but you need the tools installed on your machine. 9i is getting a bit dated though.

When you start making linked lists the use becomes a bit more obvious. Or if you wanted to pass a variable to a function and be able to change it's value.
 
Back
Top