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
I need to implement a mini version of linux''s ''tar'' function in C.

steric in square

Using the Constructor There are basically three ways of creating and initializing the object. The first way to call the constructor is explicitly as :

A:BinaryHeap.h ------------ #ifndef BINARY_HEAP_H_ #define BINARY_HEAP_H_ #include "dsexceptions.h" #include "vector.h" // BinaryHeap class // CONSTRUCTION: wi

find largest clique present in graph

Byteland county is very famous for luminous jewels. Luminous jewels are used in making beautiful necklaces. A necklace consists of various luminous jewels of particular colour. Nec

find area uder the curve y=f(x) between x=a and x=b   #include float start_point, /* GLOBAL VARIABLES */ end_point, total_area; in

Charity Ball Organizer Many charities support good causes, but one of the difficulties each of them has is organizing their fundraising events. After nearly a semester of C progra

Write a program to find the area under the curve y = f(x) between x = a and x = b, integrate y = f(x) between the limits of a and b. The area under a curve between two points can b

Explain Operators in C Language? The C language is very rich in built - in - operators and it places more significance on operators than do most other computer languages. The C