SJ posted:
Hi:
I am reviewing some bad code. Help me on this! The following is a
modified version of the code.
whie(some condition)
{
char *x;
x = new char(' ');
foo(x);
}
The variable x is not deleted. So, there is a memory leak?
This code sometimes crashes with a "memory could not be read" problem.
I suspect this is caused by either:
A) An invalid pointer, like the following:
int* p_k;
//p_k now contains gibberish
*p_k = 4;
B) Running out of memory
for(;
{
char* p_k = new char;
}
Can anyone explain me the internals of how memory is handled and what
causes the problem?
When you define a variable as follows:
int main()
{
int k = 4;
}
Then you don't have to worry about deallocating the memory, it gets done
automatically. "int k = 4;" is really an abbreviation of:
int auto k = 4;
("auto" as in it's taken care of automatically)
Moving on, there's a thing called "dynamic memory allocation". The thing
here is that you have complete control over when, where, how, who, what, and
why memory is allocated. So let's say I allocate some memory dynamically:
int main()
{
int* p_k = new int;
}
I dictate when and where it will be deallocated. In the above, the memory
for "p_k" is deallocated at the end of main, as it's an automatic variable,
ie.:
int* auto p_k = new int;
However, the memory allocated by the expression "new int" is never
deallocated. To deallocate it, I would do the following:
int main()
{
int* p_k = new int;
delete p_k;
}
That's simply how it works: With automatic variables, you just decide when
they're made and they get killed off automatically when you no longer need
them (ie. at the end of their scope). But with dynamic memory allocation,
you have exact duress over what's going on.
Which leads me onto the concept of "Garbage Collection". Garbage Collection
is something that's hyped up a lot by stupid people. For instance, have you
noticed how with every version of Windows, it gets more dumbed down and more
dumbed down. You open a menu in WinXP and it doesn't even show you the whole
contents of the menu, it just (very annoyingly) shows you the most used
elements. Anyway, the idea behind Garbage Collection is as follows:
int main()
{
int* p_k = new int;
}
Even though I haven't deallocated the dynamically allocated memory, it still
gets deallocated when the program ends by the "Garbage Collector".
Well, C++ isn't quite as dumbed down, but one can make a Garbage Collector
in C++ by overloading the operators "new" and "delete" with their own code
that (inefficiently) takes care of things.
Alternatively, if you want something very simple:
#include <memory> //not sure if that's the right header
int main()
{
std::auto_ptr<int> p_k = new int;
}
In the above we sort of have a Garbage Collector. The class "auto_ptr"
cleans things up for us when the automatic variable, ie.:
std::auto_ptr<int> auto p_k = new int;
goes out of scope.
-JKop