Advantage of automatic memory management--> Demo
In c language we have to explicitly deallocate the memory after use. Folowing is a set of C code which runs an infinite loop.
#define LEN 10000
void fun()
{
char *p;
p = malloc(LEN);
if(p == 0) {
perror("malloc failed");
exit(1);
}
free(p);
}
main()
{
/* call "fun" in an infinite loop */
while(1) {
fun();
}
void fun()
{
char *p;
p = malloc(LEN);
if(p == 0) {
perror("malloc failed");
exit(1);
}
free(p);
}
main()
{
/* call "fun" in an infinite loop */
while(1) {
fun();
}
}
In this case the CPU is fully engaged but the memory consumption remains almost constant because as soon as the memory is allocated it is deallocated using free().
After the program is terminated....
This is another example where memory is not deallocated... Careful the system might get stuck...
#include <stdlib.h>
#define LEN 10000
void fun()
{
char *p;
p = malloc(LEN);
if(p == 0) {
perror("malloc failed");
exit(1);
}
}
main()
{
while(1) {
fun();
usleep(10);
#define LEN 10000
void fun()
{
char *p;
p = malloc(LEN);
if(p == 0) {
perror("malloc failed");
exit(1);
}
}
main()
{
while(1) {
fun();
usleep(10);
/* slow down the loop a little bit */
}
}
}
}
Here the memory runs out..
Where as running this python code we get the same result as in the first program..
while True:
a = [1] * 1000000
a = [1] * 1000000
First a list is created and a referenced to it. when a is again referenced to another list then the first list is unreferenced and is not accessible hence it is automatically deleted or removed from the memory








0 comments:
Post a Comment