Dynamic Memory Allocation for Single Variables

Hi Guys,
I was having a little trouble with dynamic memory allocation. Can anyone please tell me what is the purpose of dynamically allocating a single variables, like this:

1
2
3
4
5
int *Pointer = new int;
*Pointer = 7;

delete Pointer;
Pointer = 0;

Can anyone please tell me what is the purpose of dynamically allocating a single variables


A dynamic variable really does not have any big advantage over regular variable's except the fact that you are able to delete them in case you want to free some ram(I am not even sure if that a legitimate thought).
Last edited on
closed account (zb0S216C)
tejas1995 wrote:
Can anyone please tell me what is the purpose of dynamically allocating a single variables

DMA (Dynamic Memory Allocation) is the process of allocating memory from the heap (RAM), and not the stack.
Basic types, such as int, char, and float, don't require memory from the heap, but instead, they should be placed on the stack (automatic variables). Large structures, or types, should be placed on the heap.

Wazzak
As Framework says, you have a small amount of stack space. Huge allocations (like very big arrays) have to be allocated dynamically as they simply cannot fit in the stack.

Factors was on the right track; you have to delete them yourself, but the key point there is that they keep existing until you do that yourself.

This function is broken:

1
2
3
4
5
int* returnArray()
{
  int array[5];
  return array;
}

because the 5 int values will be written over once the function ends.

This function is not broken
1
2
3
4
5
int* returnArray()
{
  int* array = new int[5];
  return array;
}

because the 5 int values will be untouched until you delete.
Last edited on
Thank you .... also, can dynamically allocated variables be accessed outside the scope ? Like:

1
2
3
4
5
6
7
8
{
        {
                int *Ptr = new int;
                *Ptr = 7;
        }
 delete Ptr;
 Ptr = 0;
}
Nope. That's a memory leak. Ptr doesn't exist in the scope in which you tried to delete it.

1
2
3
4
5
6
7
8
9
{
    int * ptr ;
    {
           ptr = new int(7) ;
           // do stuff with ptr
    }
    
    delete ptr ;
}


is fine though.

edit: Oops, forgot to new!
Last edited on
The only way of making a dynamically allocated variables hat can be accessed outside the scope is by making it a global dynamically allocated variable. That's why cire is right with.

1
2
3
4
5
6
7
8
9
{
    int * ptr ;
    {
           *ptr = 7 ;
           // do stuff with ptr
    }
    
    delete ptr ;
}
The previous two posts seem to be deleteing without having actually newed. This is bad.

This:

1
2
3
4
5
6
{
    int * ptr ;
    {
           *ptr = 7 ; // segFAULT!
    
    

will probably cause a segFault. It's bad. I presume they meant

1
2
3
4
5
{
    int * ptr ;
    {
           ptr = new int;
           *ptr = 7;

You presume correctly. Oops. =)
Topic archived. No new replies allowed.