hi
What is a memory leak? and how can we stop it?
thnks
hi
What is a memory leak? and how can we stop it?
thnks
The biggest cause of memory leaks for beginner programmers is stray pointers. Stray pointers occur when you lose focus of a pointer but don't delete the variable it pointedto on the heap. The variable will still be on the heap until the program exits but you will have no way to destroy it or access it.
Code:#include "stdafx.h" #include <iostream> using namespace std; int main(int argc, char* argv[]) { //created on the heap. The new operator returns a pointer to the //80 chars on the heap. If the delete operator is not used on the //pointer the allocated memory will exist until the program exits. //The delete operator will give the allocated memory back to the //heap. The delete operator should be called when the memory is //no longer needed else it is considered a leak. char * pHeapChar = new char[80]; if( pHeapChar ) { delete [] pHeapChar; } else { cout << "Insufficient memory error " << endl; } //created on the stack no memory leak possible char Stack[80]; char * pStackChar = Stack; pStackChar = &Stack[0]; //same a above return 0; }
Any local or global automatic variables are on the stack and cannont cause a memory leak.
What's a stack? Heard about it before, but never understood what it is...
MagosX.com
Give a man a fish and you feed him for a day.
Teach a man to fish and you feed him for a lifetime.
A stack is a first in last out (filo) data structure. This allows for scoped variables. That is automatic variables to be placed on the stack while in a programming block. When that block is left those variables are popped off the stack. In actuality their left there but the stack pointer is moved down and those location are made availible for the next variables.