Wednesday, 3 November 2010

Memory Management with 'new'

Sometimes it is useful to take memory management in our control to make sure we have the right amount of memory already reserved in advance. This could be to speed up memory allocation/deallocation or for debugging purpose where contiguous memory allocation can speed up debugging or for variety of reasons.

The following example shows one way in which memory can be reserved in a chunk for the program.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

class
Class
{

public
:
int
x;
char
y;
bool
z;
};


int
main()
{

unsigned char
tempBuf[100];
cout<<"Pointer for tempBuf = " << &tempBuf << endl;

Class* c = new (tempBuf) Class;
cout<<"Pointer for c = " << c << endl;

return
0;
}




The output is as follows:

3 comments:

  1. hi in this case memory will still allocate in stack. Am I correct?

    ReplyDelete
  2. Dinesh - Any dynamic memory you allocate is always in heap. Data which is declared within a function are in the stack. So for example

    [code]
    int main()
    {
    int a , b;
    ..
    ..
    int *p = foo( a, b );
    }

    int *foo( int a, int b )
    {
    int *p = new int[10];
    return p;
    }
    [/code]

    In the above case variable 'a' and 'b' are declared in the stack but pointer 'p' in the function foo is been allocated in the heap. Hence the reason you can return the pointer. You cannot return when the memory is allocated in the stack. As the stack gets cleared by when it leaves the scope.

    ReplyDelete