gold said:
Hello all,
I want know abt wht kind of datastructures using both C & C++ internally.
Some were said heap, others said tree
anyone can explain brief?
Your question is senseless. The "opposite" of a heap is a stack.
if you call a function in a C program (you call at least the main function) all
instructions and data is put on a stack. This stack is then processed from the
top to the bottom by the CPU. After having processed all instructions of the
function, the stack is deleted again.
There's one exception: the call of malloc (C) or new (C++). malloc and new
reserve memory on the heap (which is a different memory area then the stack) and
return a pointer to this memory area.
now watch this example:
void func(){
char *ptr = (char*)malloc(sizeof(char));
}
I told you, that all data and instructions are put on the stack. The pointer
*ptr is such data, thus it's put on the stack, but the data the pointer is
pointing to, is on the heap (because it's reserved by malloc).
As soon as the function returns, the stack will be deleted - including the
pointer, but the memory on the heap will still be there. With the deletion of
the pointer you've lost the information where this data is stored. This is
called a memory leak.
There are two things, you have to do:
1. delete the reserved memory:
void func(){
char *ptr = (char*)malloc(sizeof(char));
//... do something
free (ptr);
}
2. if you still need the data structure, which is on the heap, after the
function has returned, return the pointer to this datastructure:
char* func(){
char *ptr = (char*)malloc(sizeof(char));
//... do something
return ptr:
}
Don't forget to delete the data, as soon as don't need it any more outside the
function.
The advantage of programming with malloc and new is that you have your data
structues on the heap and you're just passing around pointers. This is great for
performance. It's also an advantage for semantic reasons, because a pointer
represents an object.
The disadvantage is the risk for memory leaks, if you forget the delelte the
reserved memory before the last pointer to this memory is deleted.
greets Boris