Sunteți pe pagina 1din 15

Memory Management in Programming Languages

Memory Management in Programming Languages


S M Anas Roll Number: 120107194 Department of Civil Engineering School of Engineering and Technology Sharda University, Gr. Noida, UP, INDIA mohdanas43@gmail.com

Abstract
This paper is a comparative description of the memory management features of the C, C++ and C# programming languages. Although there are already many comparisons of those languages, its the opinion of mine that most of them are not professional by means of objectivity. I cant hope to cover all the programming languages in the world, so I have chosen some of the languages that are widely used. I tried really hard to be objective and show the strength and weakness of programming languages on the basis of memory management features. The paper is divided into three sections; the first discusses the Introduction to memory management (Static and dynamic memory allocation), the second discusses the memory management features (Dynamic memory allocation and de-allocation) of languages like C, C++ and C#. Here, I have given an idea of run time memory allocation which helps us how to use our memory inherently or efficiently. The last section puts the pieces together and implements a commonly used structure in the programming languages and gives the difference between these languages.

Memory Management in Programming Languages

1. Introduction
Memory management is the act of managing computer memory. The essential

memory can be many times larger than the physical memory in the system, Protection Each process in the system has its own virtual address space. These virtual address spaces are completely separate from each other and so a process running one application cannot affect another. Also, the hardware virtual memory mechanisms allow areas of memory to be protected against writing. This protects code and data from being overwritten by rogue applications. Memory Mapping Memory mapping is used to map image and data files into a processes address space. In memory mapping, the contents of a file are linked directly into the virtual address space of a process. The diagram (below) showing the virtual memory with different kinds of mappings.[5,7]

requirement of memory management is to provide ways to dynamically allocate

portions of memory to programs at their request, and freeing it for reuse when no longer needed. This is critical to the computer system. Several methods have been devised that increase the effectiveness of memory management. Virtual memory systems separate the memory addresses used by a process from actual physical addresses, allowing separation of processes and

increasing the effectively available amount of RAM using paging or swapping to secondary storage. Static memory allocation refers to the process of allocating memory at compiletime before the associated program is executed, unlike dynamic memory allocation or automatic memory allocation where memory is allocated as required at run-time. The memory management subsystem

provides: [5, 6, 9]

Large Address Spaces The operating system makes the system appear as if it has a larger amount of memory than it actually has. The virtual Fair Physical Memory

Allocation

Memory Management in Programming Languages

The memory management subsystem allows each running process in the system a fair share of the physical memory of the system, malloc( )

Allocates request size of bytes and returns a pointer to the first byte of the allocated space Allocates space for an array of

2. Memory management
2.1. C concepts
C language requires the number of elements in an array to be specified at compile time. But we may not be able to do so always. Our initial judgement of size, if it is wrong, may cause failure of the program or wastage of memory space. Many languages permit a programmer to specify an arrays size at run time. Such languages have the ability to calculate and assign, during execution, the memory space required by the variables in a program. The process of allocating memory at run time is known as dynamic memory allocation. Although C does not inherently have this facility, there are four library routines known as memory management functions that can be used for allocating and freeing memory during program

calloc( )

elements, initializes them to zero and then returns a pointer to the memory.

free( ) realloc( )

Frees previously allocated space. Modifies the size of previously allocated space.

2.1.1. malloc( ) function in C


The name malloc stands for memory allocation. The function malloc( ) reserves a block of memory of specified size and return a pointer of type void which can be casted into pointer of any form.

Syntax of malloc( )
ptr = (cast_type*) malloc (byte_size);

Here, ptr is pointer of cast-type. The malloc( ) function returns a pointer to an area of memory with size of byte size. If sufficient memory is not available in heap then allocation fails and malloc( ) returns NULL pointer. Listing-1, illustrate the

execution. These are listed in Table 1.1. These functions help us build complex application programs that use the available memory intelligently. [1]

Table 1.1 Memory Allocation Functions Function Task

concept of malloc( ) function in C. [1]

Memory Management in Programming Languages

Listing 1: malloc( ) function in C

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

#include<stdio.h> #include<string.h> #include<stdlib.h>

int main( ) { char *mem_alloc; /*memory is allocated dynamically*/ mem_alloc = malloc (20 * sizeof(char) ); if (mem_alloc==NULL) { printf (Couldnt able to allocate requested memory\n); } else { strcpy( mem_alloc,fresh2refresh.com); } printf (Dynamically allocated memory content: %s\n, mem_alloc ); free (mem_alloc); return 0; } Output:

Dynamically allocated memory content: fresh2refesh.com

2.1.2. calloc( ) function in C


The name calloc stands for "contiguous allocation". It is used to allocate multiple

block of memory. It is similar to malloc( ) except two difference The first one is that it takes two arguments.

Memory Management in Programming Languages

The first argument specifies the number of block and second one specifies the size of each block.

malloc( ) contains garbage value while memory allocated by calloc contains zero (0) value. Like malloc( ), calloc( ) also returns NULL pointer if there is no

Syntax of calloc( )
ptr = (cast_type*) calloc (n, elem_size);

sufficient memory available in the heap. Listing-2, illustrate the concept of calloc( ) function in C. [1]

The other difference between calloc( ) and malloc( ) is that memory allocated by Listing 2: calloc( ) function in C

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

#include<stdio.h> #include<string.h> #include<stdlib.h>

int main( ) { char *mem_alloc; /*memory is allocated dynamically*/ mem_alloc = calloc( 20, sizeof(char)); if (mem_alloc==NULL) { printf (Couldnt able to allocate requested memory\n); } else { strcpy (mem_alloc,way2sms.com); } printf (Dynamically allocated memory content: %s\n, mem_alloc); free (mem_alloc); return 0;

Memory Management in Programming Languages

21

} Output:

Dynamically allocated memory content: way2sms.com

2.1.3. free( ) function in C


Compile-time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic run-time allocation, it is our responsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited. So, the function free( ) is used to release the memory space allocated

To release an array of memory that was allocated by calloc( ) we need only to release the pointer once.

2.1.4. realloc( ) function in C


The name realloc stands for reallocation of memory. The realloc( ) is used when we want to increase or decrease the memory size already allocated by malloc( ) and calloc( ). It alters the size of the memory block without losing the old data. This process is called the reallocation of

dynamically. [1]

Syntax of free( )
free (ptr);

memory.

Syntax of realloc( )
ptr = (cast_type*) realloc (ptr, new_size);

Here, ptr is a pointer to a memory block, which has already been created by malloc( ) or calloc( ). Note: Use of an invalid pointer in the call may create problems and cause system crash. We should remember two things here: It is not the pointer that is being released. The function takes two argument, first is a pointer to the block of memory that are previously allocated by malloc( ) or calloc( ) and second one is the new size for that block. Listing-3, illustrate the concept of realloc( ) function in C. [1]

Listing 3: realloc( ) function in C

Memory Management in Programming Languages

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

#include<stdio.h> #include<string.h> #include<stdlib.h> int main ( ) { char *mem_alloc; /*memory is allocated dynamically*/ mem_alloc = malloc (20 *sizeof (char)); if (mem_alloc==NULL) { printf (Couldnt able to allocate requested memory\n); } else { strcpy ( mem_alloc,ibibo.com); } printf (Dynamically allocated memory content: %s\n, mem_alloc); mem_alloc = realloc (mem_realloc, 100*sizeof (char)); if (mem_alloc==NULL) { printf (Couldnt able to allocate requested memory\n); } else { strcpy (mem_alloc,space is extended up to 100 characters); } printf (Resized memory: %s\n, mem_alloc); free (mem_alloc); return 0; }

Memory Management in Programming Languages

Output: Dynamically allocated memory content: ibibo.com Resized memory: space is extended up to 100 characters

2.2.

C++ concepts

requirement is handled by the compiler. [2, 3, 8]

The C++ programming language does, per default, not use garbage collection. But in contrast to other languages, there are three different locations where objects can be placed: In the static memory On the stack (local store) On the heap (free store) The following sections will explain the differences between these locations, how they can be combined and which benefits can be gained from this.

2.2.2. Object on the stack


Objects located on the stack are fully managed by the compiler. There is no need to manually allocate memory of delete them when they are no longer used. To allow the compiler to take care of this details there are some limitations: only static sized objects (objects for which the size is known at compile time) and objects whose lifetime does not exceed the block they are declared in, can be placed on the stack. Listing 4 demonstrates two objects (integer values) placed on the stack. The x variable is Listing 4: C++ Allocation on the stack 1 2 3 4 5 6 7 void StackAlloc ( ) { int x (0); { x = 3; int y(x); ++y;

2.2.1. Static objects


Objects in the static memory are objects which are created on start of the program and will be available until the program terminates. Global and namespace variables are always placed in the static memory, as well as class or function variables with the static modifier. Static objects are constructed only once at program start up and deleted on normal program termination. The memory

Memory Management in Programming Languages

8 9 10 x ++; }

} 2.2.3.1. Dynamic Memory Allocation using new operator in C++ An object can be created using the new

declared in line 3 and exists until the block in which it was declared ends (line 10). Between its declaration and the block end in line 10 the variable can be used. The y variable is constructed in line 6 and becomes destroyed in line 8. As you can see the construction of the objects is done explicit, but the destruction is done automatically by the compiler. The compiler will call the destructor of the objects which went out of scope in reverse order of their construction. If a constructor throws an exception, the corresponding destructor will not be called (only successfully constructed objects can be destructed). It is an important fact that objects on the stack cannot leak.

operator. The new operator allocates specific amount of memory from the free store during execution time and returns the starting address of the block allocated to a pointer. new is a keyword in C++.

Syntax of new operator


pointer_variable = new data_type; pointer_variable = new class_name; pointer_variable = new data_type [SIZE];

Here, pointer variable is a pointer to the data_type (int, float, etc) specified after the keyword new and it collect the address of the memory block allocated by the new operator and the SIZE is number of elements the array is suppose to hold. This indicates the actual memory blocks that has to be allocated dynamically and the class_name is the abstract data type which forms the data type of the class object. Listing 5 illustrate the concept of new operator in C++. [2]

2.2.3. Objects on the heap


Objects on the heap are dynamically allocated at runtime. The C++ language provides the new operator to allocate dynamic memory. An object created with the new operator exists until it is explicitly destroyed using the delete operator.

Listing 5: To Allocate an Array Dynamically

Memory Management in Programming Languages

1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

#include <iostream.h> #define SIZE 2; using namespace std; int main ( ) { int *p, i; p = new int [SIZE]; // allocating memory for an arrray cout <<Enter the values<<endl; for ( i=0; i<SIZE; i++) { cin >> p[i] ; } cout << The numbers are <<endl; for ( i=0; i<SIZE; i++ ) { cout << p[i] << endl; } delete p; return 0; } Output:
Enter the values 2 3 The numbers are 2 3

10

Memory Management in Programming Languages

2.2.3.3. Dynamic Memory De-allocation using delete operator in C++ The object created by new, i.e., the memory allocated for certain variable, by new operator has to be de-allocated once its purpose is over. This is done by the delete operator; delete operator destroys the

If the object, or any part of it, cannot be accessed by any possible

continuation of execution, other than the running of destructors, the object is considered no longer in use and it becomes eligible for destruction. The C# compiler and the garbage

created object to release the memory space for future use. delete is a keyword in C++. Listing 5 also illustrate the concept of delete operator in C++. [2, 3]

collector may choose to analyze code to determine which references to an object may be used in the future. Once the object is eligible for destruction, at some unspecified later time the destructor (if any) for the

Syntax of delete operator


delete pointer_variable; delete [SIZE] pointer_variable;

object is run. Unless overridden by explicit calls, the destructor for the object is run once only. Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any possible

2.3. C# concepts
C# employs automatic memory management, which frees developers from manually allocating and freeing the memory occupied by objects. Automatic memory management policies are implemented by a garbage collector. The memory management life cycle of an object is as follows: [4] When the object is created, memory is allocated for it, the constructor is run, and the object is considered live.

continuation of execution, including the running of destructors, the object is considered inaccessible and the object becomes eligible for

collection. Finally, at some time after the object becomes eligible for collection, the garbage collector frees the memory associated with that object. [4]

11

Memory Management in Programming Language

2.3.1. Automatic Garbage Collection


The CLR (Common Language Runtime) has a service called the Garbage Collector (GC), which automatically manages

The behavior of the GC can be controlled, to some degree, via static methods on the class System.GC. This class can be used to request a collection to occur, destructors to be run (or not run), and so forth. [4, 7]

memory for you. [4, 7] The GC automatically deletes objects from memory that your program wills no longer access. The GC relieves the programmer of tasks that he or she has traditionally had to perform, such as de-allocating memory and hunting for memory leaks. This is no small feature, since hunting for memory leaks can be difficult and time-consuming. The GC maintains information about object usage, to and make uses this

3. final comparison
So whats better? It depends. In that case, the best technology depends on the size of the project. For smaller projects the ANSI C memory management features will be fully sufficient and just more-straight. For big projects the C++ and C# become memory more

management

features

interesting, since C++ allows us to choose how to allocate memory for a particular instance while C# allows automated deallocation of memory. [4, 7, 8, 9, 10]

information management

memory such as

decisions,

where in memory to locate a newly created object, when to relocate an object, and when an object is no longer in use or inaccessible. To have a comparison of these languages, we make a table for easy understanding.

12

Memory Management in Programming Language

S.NO.

Description

C++ High level of Abstraction but better than C. Done by programmer.

C#

1.

Abstraction

Low level of Abstraction.

High level of Abstraction. Automatically done. C# does not allow you to choose how

2.

Deallocation

Done by programmer.

C allows us to choose 3. Memory allocation how to allocate memory for a particular instance. Similar as C.

to allocate memory for a particular instance.

Dynamic memory allocation and de4. Function allocation are done by malloc( ), calloc( ) & realloc( ) and free( ) . Memory leakage is a big problem in C.

Dynamic memory allocation and de allocation are done by new and delete operator

Dynamic memory allocation is done by garbage collector and de allocation automatically. No memory leakage in C#.

5.

Leakage

Similar as C.

which

makes

programmer

to

handle

Conclusion
As the requirement increases for the memory management rapidly, we move towards new modification then an increment version of C is produced called as C++ which has more memory management features then C. After sometimes a new modified version C# is came which is more efficient then C++

memory more efficiently then C and C++. I have compared the memory management features of C, C++ and C# programming language that gives an idea that C and C++ allows us to choose how to allocate memory for a particular instance while C# does not allow it. I have also concluded that deallocation of memory in C and C++ is done

13

Memory Management in Programming Language

by the programmer only while in C# automated de-allocation of memory is done. In C#, garbage collection makes data sharing easier. Applications are sometimes built which require object sharing. Problems can arise in defining responsibilities for clean-up: if object A and object B share pointer C, should A delete C, or should B? This eliminates the problem: neither A nor B should (or could) delete C using either C#.

Both A and B use C as long as they need to, then the system is responsible for disposing of C when it is no longer referenced by either (or any other). Naturally, the

developer still must be concerned about critical sections while accessing shared data and this must be handled in some standard way. [11]

14

Memory Management in Programming Language

References
1. E Balagurusamy (2007). Programming in ANSI C. New Delhi, INDIA: Tata McGraw Hill Education Private Limited. 2. M.T. Somashekara, D.S. Guru, H.S. Nagendraswamy & K.S. Manjunatha (2012). ObjectOriented Programming with C++. New Delhi, INDIA: Ashok K.Ghosh, PHI Learning Private Limited, fourth edition. 3. Bjarna Stroustrup (1997). The C++ Programming Language. New York: Addison Wesley, third edition. 4. E Balagurusamy (2008). Programming in C#. New Delhi, INDIA: Tata McGraw Hill Eductaion Private Limited. 5. 6. Memory Management. Retrieved from http://en.wikipedia.org/wiki/Memory_management . Memory Management. Retrieved from http://www.slideshare.net/shrikantv/memorymanagement-in-c .

7.

Difference between C, C++ and C# on the basis of Memory Management. Retrieved from http://www.google.com .

8.

A practical comparison of the Java and C++ resource management facilities. Research Paper by Markus Winand.

9.

Protection traps and alternatives for memory management of an object-oriented language. Research Paper by Antony L. Hosking & J. Eliot B. Moss.

10.

Object-Oriented Programming versus Abstract Data Types. Research Paper by William R.Cook.

11.

C++

and

C#:

Comparing

Programming

Languages.

Retrieved

from

http://msdn.microsoft.com/en-us/library/ms836794.aspx. 12. Difference between C# and C++.


http://www.rapidprogramming.com/questions-

answers/What-is-the-difference-between-C-Sharp-and-C-plus-plus--713 .

15

S-ar putea să vă placă și