0% found this document useful (0 votes)
2 views22 pages

Computer Methods C Programming

Lecture 11 covers dynamic storage allocation in programming, detailing storage classes such as local, register, and static variables, and their attributes like storage duration and scope. It introduces functions for dynamic memory management, including malloc, calloc, realloc, and free, emphasizing the importance of managing memory effectively to prevent errors. Examples illustrate the allocation and deallocation of memory for various data structures, demonstrating practical applications of these concepts.

Uploaded by

Thabiso Kyle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Computer Methods C Programming

Lecture 11 covers dynamic storage allocation in programming, detailing storage classes such as local, register, and static variables, and their attributes like storage duration and scope. It introduces functions for dynamic memory management, including malloc, calloc, realloc, and free, emphasizing the importance of managing memory effectively to prevent errors. Examples illustrate the allocation and deallocation of memory for various data structures, demonstrating practical applications of these concepts.

Uploaded by

Thabiso Kyle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

COMPUTER METHODS 1

LECTURE 11

Dynamic Storage Allocation

1 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Storage Classes

The compiler and/or the linker allocates the pieces of storage


in which we store data. Each piece has an identifier as set out
when we declare variables.
The attributes of variables include: name, type, size, and
value.
Identifiers are also used as name for user-defined functions.
Each identifier in a program has other attributes, including
storage class, storage duration, scope, and linkage.
Storage class indicated in C by storage class specifiers
(auto, register, extern, and static)

2 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Storage Classes(cont’d)

An Identifier’s storage class determines its


storage duration which is the period during which the identifier
exists in memory.
scope which is where the identifier can be used in the program.
linkage determines for a multiple-source-file program whether
the identifier is known only in the current file or any other file
with proper declarations.
There are generally 3 storage classes: Local variables, Register
variables, Static variables

3 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Local Variables: internal automatic variables

This is a default storage class for variables declared within a


compound statement; storage is allocated at the time of the
declaration and is released when control leaves the enclosing
compound. The keyword auto is rarely used.
Example:
{
int anInteger; /* storage allocated for anInteger */
float aFloat; /* storage allocated for aFloat */

/* executable statements */
{
int innerInt; /* storage allocated for innerInt */
/* executable statements */
}
/* storage for InnerInt released */
/* more executable statements */

}/* storage for anInteger and aFloat released */

4 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Local Variables: Formal Arguments to Functions

These are similar to internal automatic variables


with storage allocated on entry to the function
and released when control leaves the function.
One difference is that each formal argument is
initialized with the value of the corresponding
actual argument whereas internal variables may
be uninitialized

5 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Register Variables

Data in the machine-language version of a program is normally


loaded into registers for calculations and other processing.
Normally used to maintain the variable in one of the
computer’s high-speed hardware registers, to avoid repetitive
transfer from memory to register, that could drop the
performance of the computation.
Often in modern compiler the keyword register is ignored.
The following declaration suggests that the integer variable
counter be placed in one of the computer’s registers and
initialized to 1
register int counter = 1;

6 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Static Storage Class

Keywords extern and static are used in the declarations of


identifiers for variables and functions of static storage
duration.
It is sometimes desirable to preserve the value and thus the
storage allocated to an internal variable between consecutive
invocation of a function.
This is achieved by prefixing the declaration of the variable by
the keyword static.
Global variables and functions are of storage extern by
default.
Global variables are created by placing variable declarations
outside any function definition, and they retain their values
throughout the execution of the program.

7 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Static Storage Class(cont’d)

In the following program, the variable pageNumber is local to


the function printHeading() but it has static storage class, its
value is then preserved from one call of the function to the
next.
Example:
/* - cm11_10_5.c - Internal Static Variables */
void printHeading(const char *aHeading);
main()
{
printHeading("The title page"); The following is the result of
printHeading("A general page"); an execution of the program:
printHeading("The last page");
} The title page Page 1
void printHeading(const char *aHeading) A general page Page 2
{ The last page Page 3
static int pageNumber =1;
printf("%s\tPage %d\n", aHeading, pageNumber);
pageNumber++;
}

8 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Dynamic Allocation of Storage
There are times when the programmer wishes to exercise more
precise control on when the storage is allocated and when it is
released. A group of functions of the standard library is
provided for this purpose:
#include <stdlib.h>
void * malloc(size_t size);
void * calloc(size_t n, size_t size);
void * realloc(void *ptr, size_t size);

void free(void *ptr);

The type size_t is defined in the header file stddef.h as an


unsigned integral type which the operator sizeof produces.
A typical entry of stdlib.h will be;
typedef unsigned int size_t;

9 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Exiting a program

The following instruction is used to exit from a program


void exit(int status);
Sometimes an error occurs and we want the program to
immediately exit
The exit function closes all open files, frees all allocated
memory, and exits the program
Equivalent to calling ”return” within main
Remember to insert
#include <stdlib.h>

10 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


The malloc function

The function malloc() allocates space for an object of size


bytes and returns a pointer to this object. The syntax is
void * malloc(size_t size);

If it is unable to allocate the requested space, it returns


NULL.
You should always check whether memory was successfully
allocated
Remember to insert #include <stdlib.h>

11 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Why casting?

The casting in
y = (int *)malloc(n*sizeof(int));
is needed because malloc returns void * :
void * malloc(unsigned int nbytes);
The type (void *) specifies a generic pointer, which can be
cast to any pointer type.

12 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


What does ”sizeof” do?

The sizeof operator gets a variable or a type as an input and


outputs its size in bytes:
double x;
s1=sizeof(x); /* s1 is 8 */
s2=sizeof(int) /* s2 is 4 */

13 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Free the allocated memory segment

The following function is used to free an allocated space in


memory:
void free(void *ptr);

free(p) to free the allocated memory pointed to by p


If p doesn’t point to an area allocated by malloc, a run-time
error occurs
Always remember to free the allocated memory once you
don’t need it anymore; Otherwise, you may run out of
memory before you know it!

14 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Example

Let us have the following declarations


#define MaxName 20
typedef struct{ char name[MaxName];
int age;
float height;
} Person;
int *ptr;
Person employee;
Person *ptrPerson = &employee;

we can then have the following pieces of codes:


ptr = (int *)malloc(sizeof(int)); /* allocate space for an int*/
if(ptr == NULL)
{
printf("out of storage\n");
exit(EXIT_FAILURE);
}
else
{
*ptr =37;
...
}
15 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation
Example (cont’d)

if((ptrPerson =(Person *) malloc(sizeof(Person))) == NULL)


{
printf("outside of storage\n");
exit(EXIT_FAILURE);
}
else
{
ptrPerson->age = 18;
...
}

16 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Example:free the space allocated

At some stage, but necessarily in the function which calls


malloc(), the space allocated using malloc() for the object
can be released by using the free() function.
For the pointers ptrPerson and ptr allocated previously the
spaces will be freed by the following instructions
free(ptrPerson);
free(ptr);

17 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


calloc() function

The function calloc() allocates space for an array of n


elements each of size bytes.
A most important difference from malloc() is that calloc()
initializes the allocated space to zeroes whereas malloc()
leaves the spaces unitialised.

18 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Example

/* an array of 20 Persons initialised to zeros /


ptrPerson = (Person *)calloc(20, sizeof(Person));

/* an uninitialised array of 20 Persons */


ptrPerson = (Person *)malloc(20*sizeof(Person));

/* a single Person initialised to zeros */


ptrPerson = (Person *)calloc(1, sizeof(Person));

/* a single uninitialised Person */


ptrPerson = (Person *)malloc(sizeof(Person));

19 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Use of space allocated with malloc and calloc

Once space for an array has been allocated, it can be accessed


in the usual ways by subscript or pointer:
Person *ptrPerson;
Person *thisOne;
int index;

ptrPerson =(Person *)calloc(20, sizeof(Person));


if(prtPerson == NULL)
exit(EXIT_FAILURE);

/* Access using subscript */


for(index = 0; index <20; index++)
process(ptrPerson[index]);

/* Access using pointers */


for(thisOne = ptrPerson; thisOne <ptrPerson+20; thisOne++)
process(*thisOne);

20 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


function realloc()

The function realloc() changes the size of the object to which ptr points
and allocates size bytes which may be larger or smaller than the one
originally allocated.
The original contents of the space are preserved, being copied if necessary.

21 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation


Your To Do work

1 Read your lecture 11


2 Complete Practical 6

22 / 22 Computer Methods 1 Lecture 11: Dynamic Storage Allocation

You might also like