Memory management in C programming Essay

[ edit ] Memory Management

In C, you have already considered making variables for usage in the plan. You have created some arrays for usage, but you may hold already noticed some restrictions:

§ the size of the array must be known beforehand

§ the size of the array can non be changed in the continuance of your plan

We Will Write a Custom Essay Specifically
For You For Only $13.90/page!

order now

Dynamic memory allocationin C is a manner of besieging these jobs.

[ edit ] Malloc

# include & amp ; lt ; stdlib.h & A ; gt ;

null *calloc ( size_t nmemb, size_t size ) ;

null free ( null *ptr ) ;

null *malloc ( size_t size ) ;

null *realloc ( null *ptr, size_t size ) ;

The C functionmallocis the agencies of implementing dynamic memory allotment. It is defined in stdlib.h or malloc.h, depending on what runing system you may be utilizing. Malloc.h contains merely the definitions for the memory allotment maps and non the remainder of the other maps defined in stdlib.h. Usually you will non necessitate to be so specific in your plan, and if both are supported, you should utilize & A ; lt ; stdlib.h & A ; gt ; , since that is ANSI C, and what we will utilize here.

The matching call to let go of allocated memory back to the operating system isfree.

When dynamically allocated memory is no longer needed, freeshould be called to let go of it back to the memory pool. Overwriting a arrow that points to dynamically allocated memory can ensue in that information going unaccessible. If this happens often, finally the operating system will no longer be able to apportion more memory for the procedure. Once the procedure issues, the operating system is able to liberate all dynamically allocated memory associated with the procedure.

Let ‘s look at how dynamic memory allotment can be used for arrays.

Normally when we wish to make an array we use a declaration such as int array [ 10 ] ;

Recallarraycan be considered a arrow which we use as an array. We specify the length of this array is 10ints. After array [ 0 ] , nine other whole numbers have infinite to be stored consecutively.

Sometimes it is non known at the clip the plan is written how much memory will be needed for some informations. In this instance we would desire to dynamically apportion required memory after the plan has started put to deathing. To make this we merely need to declare a arrow, and invoke malloc when we wish to do infinite for the elements in our array, or, we can state malloc to do infinite when we foremost initialise the array. Either manner is acceptable and utile. Previous Page|Next Page


Operating Systems


1. Introduction

2. Abbreviated Boot

3. The Boot Process

4. Startup and Run Levels

5. Low-level formatting Scripts

6. Runlevel Scripts

7. Login Procedure

8. Bash Shell

9. Filesystems

10. LILO, Kernel and Root Filesystem

11. The Kernel

12. Passwords, Users, Groups, and Quotas

13. The Environment

14. The /etc/sysconfig directory

15. The /proc filesystem

16. Procedure Control

17. Devicess

18. Devils Servicess

19. Inetd and Network Services

20. Plans and Libraries

21. Security and PAM

22. The pressman services

23. Sneak support with gpm

24. Mail

25. Newss

26. UUCP

27. LDAP

28. NFS and RPC

29. Samba, NetBIOS, WINS, nmbd

30. Identd ( auth )

31. Telnet and FTP

32. Apache web waiter

33. DNS and named

34. How Ten Plants

35. Ten Scripts

36. Support for Text

37. Keymapping for Programs

38. Keycode Table

39. Example Keymap File

40. Terminfo Commands

41. VT100 ESC sequences

42. Kernel Revisited

43. Configuration Files

44. Creditss


Operating Systems


Linux Process direction

Process control and the ability for inter procedure communicating is handled by the Linux meat.

Tools for working with procedures

* accton – Turns process accounting on and off. Uses the file /var/log/pacct. To turn it on type “ accton /var/log/pacct ” . Use the bid with no statements to turn it off.

* kill – Kill a procedure by figure

* killall – Send a signal to a procedure by name

* lastcomm ( 1 ) – Display information about old bids in rearward order. Works merely if process accounting is on.

* nice – Set procedure precedence of new procedures.

* PS ( 1 ) – Used to describe the position of one or more procedures.

* pstree ( 1 ) – Display the tree of running procedures.

* renice ( 8 ) – Can be used to alter the procedure precedence of a presently running procedure.

* SA ( 8 ) – Generates a sum-up of information about users ‘ procedures that are stored in the /var/log/pacct file.

* skill – Report procedure position.

* snice – Report procedure position.

* top – Displays the procedures that are utilizing the most CPU resources.

Procedure Scheduling

Computer clip on Linux systems is allocated in blink of an eyes. A jiffie is a microprocessor clip piece. On most Linux systems it is 1/100 of a 2nd. On some systems it is 1/1024 of a 2nd. The Linux meat controls process programming. There are three types of programming:

1. normal – Referred to as other, this is the scheduling type set for normal plans

2. FIFO – This is a existent clip scheduling precedence. The FIFO term means the first procedure started ( foremost in ) will be the first done ( first out ) . The lone clip this type of procedure issues is if it sleeps, is rescheduled, or if it must wait on other meat precedences to be done.

3. RR – This is a unit of ammunition redbreast type of programming, where each undertaking gets a certain sum of clip so it must go out, give control to the following undertaking and acquire back into the undertaking waiting line. This is a existent clip scheduling precedence.

Linux procedures have the undermentioned features:

1. policy – normal or existent clip. Real clip procedures have a higher precedence than normal procedures.

2. precedence – The procedure precedence. It is a figure between -20 and 19. The value of -20 is the highest, and 19 is the lowest precedence. Process precedence can be set with the nice ( 1 ) bid and changed utilizing the renice ( 8 ) bid.

Inter-Process Communication

The types of inter procedure communicating are:

1. Signals – Sent by other procedures or the meat to a specific procedure to bespeak assorted conditions.

2. Pipes – Nameless pipes set up by the shell usually with the “ | ” character to route end product from one plan to the input of another.

3. FIFOS – Named pipes runing on the footing of first informations in, foremost data out.

4. Message waiting lines – Message waiting lines are a mechanism set up to let one or more procedures to compose messages that can be read by one or more other procedures.

5. Semaphores – Counters that are used to command entree to shared resources. These counters are used as a locking mechanism to forestall more than one procedure from utilizing the resource at a clip.

6. Shared memory – The function of a memory country to be shared by multiple procedures.

Message waiting lines, semaphores, and shared memory can be accessed by the procedures if they have entree permission to the resource as set up by the object ‘s Godhead. The procedure must go through an identifier to the meat to be able to acquire the entree.


Linux Signals are:

Signal Name





Hangup ( POSIX )

Signals intelligence


Terminal interrupt ( ANSI )



Terminal quit ( POSIX )



Illegal direction ( ANSI )



Trace trap ( POSIX )



IOT Trap ( 4.2 BSD )



BUS mistake ( 4.2 BSD )



Floating point exclusion ( ANSI )



Kill ( ca n’t be caught or ignored ) ( POSIX )



User defined signal 1 ( POSIX )



Invalid memory section entree ( ANSI )



User defined signal 2 ( POSIX )



Write on a pipe with no reader, Broken pipe ( POSIX )



Alarm clock ( POSIX )



Termination ( ANSI )



Stack mistake



Child procedure has stopped or exited, changed ( POSIX )



Continue put to deathing, if stopped ( POSIX )



Stop execution ( ca n’t be caught or ignored ) ( POSIX )



Terminal stop signal ( POSIX )



Background procedure seeking to read, from TTY ( POSIX )



Background procedure seeking to compose, to TTY ( POSIX )



Pressing status on socket ( 4.2 BSD )



CPU bound exceeded ( 4.2 BSD )



File size bound exceeded ( 4.2 BSD )



Virtual dismay clock ( 4.2 BSD )



Profiling dismay clock ( 4.2 BSD )



Window size alteration ( 4.3 BSD, Sun )



I/O now possible ( 4.2 BSD )



Power failure restart ( System V )

As noted above, procedures can disregard, barricade, or catch all signals except SIGSTOP and SIGKILL. If a procedure catches a signal, it means that it includes codification that will take appropriate action when the signal is received. If the signal is non caught by the procedure, the meat will take default action for the signal.

First in first outs

First in first outs are lasting objects and can be created utilizing the mkfifo ( 1 ) or mknod ( 1 ) bid. Inside the plan, the FIFO can be created utilizing the mknod bid, so opened and read from or written to merely wish a normal file. The FIFO is usually in barricading manner when trying to execute read operations.

We besides need to cognize how much an int takes up in memory in order to do room for it ; fortuitously this is non hard, we can utilize C ‘s builtinsizeofoperator. For illustration, ifsizeof ( int ) yields 4, so oneinttakes up 4 bytes. Naturally,2*sizeof ( int ) is how much memory we need for 2ints, and so on.

So how do we malloc an array of tenints like earlier? If we wish to declare and do room in one hit, we can merely state

int *array = malloc ( 10*sizeof ( int ) ) ;

We merely need to declare the arrow ; mallocgives us some infinite to hive away the 10ints, and returns the arrow to the first component, which is assigned to that arrow.

Important note! mallocdoesnotinitialize the array ; this means that the array may incorporate random or unexpected values! Like making arrays without dynamic allotment, the coder must initialise the array with reasonable values before utilizing it. Make certain you do so, excessively. ( See subsequently the functionmemsetfor a simple method. )

It is non necessary to instantly name malloc after declaring a arrow for the allocated memory. Often a figure of statements exist between the declaration and the call to malloc, as follows:

int *array = NULL ;

printf ( “ Hello World! ! ! “ ) ;

/* more statements */

array = malloc ( 10*sizeof ( int ) ) ; /* delayed allotment */

/* use the array */

[ edit ] Error look intoing

When we want to usemalloc, we have to be aware that the pool of memory available to the coder isfinite. As such, we can conceivably run out of memory! In this instance, mallocwill returnNULL. In order to halt the plan crashing from holding no more memory to utilize, one should ever look into that malloc has non returnedNULLbefore trying to utilize the memory ; we can make this by

int *pt = malloc ( 3 * sizeof ( int ) ) ;

if ( pt == NULL )


fprintf ( stderr, “ Out of memory, exiting
” ) ;

issue ( 1 ) ;


Of class, all of a sudden discontinuing as in the above illustration is non ever allow, and depends on the job you are seeking to work out and the architecture you are programming for. For illustration if plan is a little, non critical application that ‘s running on a desktop quitting may be appropriate. However if the plan is some type of editor running on a desktop, you may desire to give the operator the option of salvaging his boringly entered information alternatively of merely go outing the plan. A memory allotment failure in an embedded processor, such as might be in a lavation machine, could do an automatic reset of the machine. For this ground, many embedded systems interior decorators avoid dynamic memory allotment wholly.

[ edit ] Thecallocfunction

Thecallocfunction allocates infinite for an array of points and initilizes the memory to zeros. The callmArray = calloc ( count, sizeof ( struct V ) ) allocatescountobjects, each of whose size is sufficient to incorporate an case of the structurestruct V. The infinite is initialized to all spots nothing. The map returns either a arrow to the allocated memory or, if the allotment fails, NULL.

[ edit ] Thereallocfunction

Thereallocfunction changes the size of the object pointed to byptrto the size specified bysize. The contents of the object shall be unchanged up to the lesser of the new and old sizes. If the new size is larger, the value of the freshly allocated part of the object is undetermined. Ifptris a void arrow, thereallocfunction behaves like themallocfunction for the specified size. Otherwise, ifptrdoes non fit a arrow earlier returned by thecalloc, malloc, orreallocfunction, or if the infinite has been deallocated by a call to thefreeorreallocfunction, the behaviour is undefined. If the infinite can non be allocated, the object pointed to byptris unchanged. Ifsizeis zero andptris non a void arrow, the object pointed to is freed. Thereallocfunction returns either a void arrow or a arrow to the perchance moved allocated object.

[ edit ] Thefreefunction

Memory that has been allocated usingmalloc, realloc, orcallocmust be released back to the system memory pool once it is no longer needed. This is done to avoid perpetually apportioning more and more memory, which could ensue in an eventual memory allotment failure. Memory that is non released withfreeis nevertheless released when the current plan terminates on most runing systems. Calls tofreeare as in the undermentioned illustration.

int *myStuff = malloc ( 20 * sizeof ( int ) ) ;

if ( myStuff! = NULL )


/* more statements here */

/* clip to let go of myStuff */

free ( myStuff ) ;


[ edit ] free with recursive informations constructions

It should be noted thatfreeis neither intelligent nor recursive. The undermentioned codification that depends on the recursive application of free to the internal variables of astructdoes non work.

typedef struct BSTNode


int value ;

struct BSTNode* left ;

struct BSTNode* right ;

} BSTNode ;

// Subsequently: …

BSTNode* temp = ( BSTNode* ) calloc ( 1, sizeof ( BSTNode ) ) ;

temp- & A ; gt ; left = ( BSTNode* ) calloc ( 1, sizeof ( BSTNode ) ) ;

// Subsequently: …

free ( temp ) ; // WRONG! do n’t make this!

The statement “ free ( temp ) ; ” will *not* free temp- & A ; gt ; left, doing a memory leak.

Because C does non hold a refuse aggregator, C coders are responsible for doing certain there is afree ( ) precisely one time for each clip there is amalloc ( ) . If a tree has been allocated one node at a clip, so it needs to be freed one node at a clip.

[ edit ] Do n’t liberate vague arrows

Furthermore, usingfreewhen the arrow in inquiry was ne’er allocated in the first topographic point frequently crashes or leads to mysterious bugs farther along.

To avoid this job, ever initialise arrows when they are declared. Either use malloc ( ) at the point they are declared ( as in most illustrations in this chapter ) , or put them to NULL when they are declared ( as in the “ delayed allotment ” illustration in this chapter ) . [ 1 ]

Previous: Arrows and arrays