Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hi!!!! Question? What is memory

Status
Not open for further replies.

kaz

Technical User
Sep 26, 2000
10
CA
Hi!!!!
Question?
What is memory leakage? and how can one prevent it.
 
A source of memory leakage occurs when memory is allocated for something but not freed. For example:
Code:
int main()
{
    for (int i=0; i<10000; ++i)
    {
         cout < DoSomething;
    }
    return 0;
}

int DoSomething()
{
    int GotIt;
    char *str;

    /* allocate memory for string */
    if ((str = (char *) malloc(10)) == NULL)
    // Do something
    return GotIt;  
}

Notice that DoSomething never frees the memory that malloc has allocated. Each time that DoSomething is called, it allocated memory for string. Eventually it could very run out of memory to allocate, then [bomb]!

Another common problem is buffer overruns. This occurs when the programmer has allocated some memory but the program allows more input that should be allowed.
Code:
int main()
{
    char str[10];
    for (int i=0; i<100; ++i)
    {
        char c;
        cin > c;
        str[i] = c;
    }
    return 0;
}[code]
[i]str[/i] only has 10 places allocated but the loop tries to stuff it with 99 characters. These are over-simplified examples and probably won't work in real life but it should give you an idea. James P. Cottingham
[COLOR=blue]
I am the Unknown lead by the Unknowing.
I have done so much with so little 
for so long that I am now qualified 
to do anything with nothing.
[/color]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top