Dynamic memory management, C/C++ Programming

C and C++ require explicit dynamic memory management, using new and delete or malloc() and free().

It is helpful to understand where variables exist (usually the stack or the heap, sometimes the data segment 1).

The stack is managed for you by the compiler, so it's usually the easiest memory to use. Local variables go on the stack, and passed function parameters go on the stack2. Since the stack frame can change signi?cantly between uses, do not return pointers to the stack! This is analogous to dereferencing freed memory.

If a variable needs to exist longer than a function call, then you should put allocate space for it on the heap (with new, for instance). If you allocate space for a variable, remember to free that space when you're done with it! If you allocate memory but don't free it, you'll end up with memory leaks, which usually becomes a problem when a program is supposed to run for a long time, repeatedly allocating and forgetting to free. It can be helpful to write allocating functions/methods at the same time as freeing functions/methods, so that you don't forget to deallocate memory from the heap.

Posted Date: 3/12/2013 4:01:06 AM | Location : United States







Related Discussions:- Dynamic memory management, Assignment Help, Ask Question on Dynamic memory management, Get Answer, Expert's Help, Dynamic memory management Discussions

Write discussion on Dynamic memory management
Your posts are moderated
Related Questions
In this problem, you will write a program that implements two algorithms for performing exact inference given a Bayesian network, namely, enumeration and variable elimination. Your


make use of class objects two calculate average

Write a function that calculates the number of elapsed days between two dates. For example the days between Feb 3, 1970 and June 21, 1980? Becareful for the Leap year.

for object, malloc allocates memory in heap however doesn't invoke object's constructor to initialize the object. new allocates memory & also invokes constructor to initialize the

Explain Processing A Data File? Mainly data file applications needs that a data file be altered as it is being processed. For instance in an application involving the processin

A string S is said to be "Super ASCII", if it contains the character frequency equal to their ascii values. String will contain only lower case alphabets (''a''-''z'') and the asci

Academic expert for Genetic Algorithm Project Description: Seeking academic expert for Genetic Algorithm. Skills required are Academic Writing, Algorithm, C++ Programming,

i am a engineering student and am working on a project in audio processing and so i have designed a FIR filter in Matlab . how can i get my Matlab program converted to C program?

Program of Binary tree: Btree::Btree(int O) : itemsInContainer(0) {     finishInit(O); }   Btree::~Btree(void) {     if( root != 0 )         delete roo