Top Banner

of 49

C-Programming-Class 6

May 30, 2018

Download

Documents

jack_harish
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/14/2019 C-Programming-Class 6

    1/49

    1

    Session 06

    Preprocessor Directories and

    Memory Allocation

  • 8/14/2019 C-Programming-Class 6

    2/49

    2

    Session Objectives

    To learn about Preprocessor directives

    To understand concept of File Inclusion

    To understand concept of Conditional Compilation

    To learn about of Dynamic Memory Allocation

    To understand concept of malloc(), calloc(), realloc(),

    free()

  • 8/14/2019 C-Programming-Class 6

    3/49

    3

    Session Topics

    Library functions and header files

    #defined and #include directives

    Macro substitution

    Conditional compilation directives

    Dynamic memory allocation

    malloc(), calloc(), realloc(), free()

  • 8/14/2019 C-Programming-Class 6

    4/49

    4

    The Preprocessor

    A preprocessor is a facility provided for writing portableprograms,easier program modifications and easier debugging.

    A preprocessor processes the source code program before itpasses through the compiler.

    The preprocessor is a part of the compiler.It is implemented asan integral part of a Standard C Compiler.

    It is a separate program which transforms C source codecontaining preprocessor directives into source code with the

    directives removed.It works on a line-by-line basis, so the end of a line meanssomething special to it.

  • 8/14/2019 C-Programming-Class 6

    5/49

    5

    Features of Preprocessors

    File Inclusions

    -- #include directive

    Substitution facilities

    -- Manifests

    -- Macros

    Conditional Compilation

    -- #if-- #else

  • 8/14/2019 C-Programming-Class 6

    6/49

    6

    Directives

    Directives are preprocessor control lines that

    control the preprocessor facilities.

    They start with the symbol #. The directives can be placed anywhere in a

    program but are most often placed at the

    beginning of a program, beforemain().

  • 8/14/2019 C-Programming-Class 6

    7/49

    7

    File Inclusion Directives

    The #include is the directive for file inclusion.

    This directive causes one file to be included in another.

    There are two ways of writing the #include directive. They are :

    #include file_name

    #include

  • 8/14/2019 C-Programming-Class 6

    8/49

    8

    #include

    #include file_name

    This command would search the directory that contains the

    source file.

    If the search fails in the home directory it searches theimplementation defined locations.

    This command would look for the file in the current

    directory as well as the specified list of directories as

    mentioned in the include search path that might have beenset up.

  • 8/14/2019 C-Programming-Class 6

    9/49

    9

    #include

    #include

    This command would search only in theimplementation defined locations

    This command would look for the file in the

    specified list of directories only

  • 8/14/2019 C-Programming-Class 6

    10/49

    10

    Substitution Facilities

    There are two types of Substitution Facilities

    available.They are:

    Manifests

    Manifest is defined as #define NAME value

    Example: #define MAX 10

    Macros

    Macro is defined as

    #define NAME(arg) expression

    Example:#define SQR(x) ((x) * (x))

  • 8/14/2019 C-Programming-Class 6

    11/49

    11

    Macro

    A macro is a simple function having its own

    syntax using #define,

    It is defined with one or a few statements.It is invoked in the same way as function call.

  • 8/14/2019 C-Programming-Class 6

    12/49

    12

    #define

    #define VALUE 25

    main()

    {

    int j;

    for(j=1;j

  • 8/14/2019 C-Programming-Class 6

    13/49

    13

    Differences:Macros & Functions

    They are expanded at pre-compile time.

    They are expanded by thepreprocessor.

    They do not follow any rules.Itis merely a replacement.

    Expressions passed asarguments can be evaluatedmore than once.

    Code used by macros cannot beused for debugging.

    They are expanded at compile

    time.

    They are parsed by the

    compiler.

    They follow all the rules

    enforced on functions.

    Expressions passed as

    arguments are evaluated only

    once.

    Code used by functions can be

    used for debugging.

    Macros Functions

  • 8/14/2019 C-Programming-Class 6

    14/49

    14

    Conditional Compilation

    A section of source code may be compiledconditionally using the conditional compilationfacilities.

    The directives used for this purpose are:

    -- #if

    -- #elseif

    -- #else

    -- #endif These directives behave much like the if-else or if-

    else-if control structure.

  • 8/14/2019 C-Programming-Class 6

    15/49

    15

    #undef, #ifdef, #ifndef, #endif

    On some occasions, it may be desirable to cause adefined name to become undefined using #undefdirective.

    #undef would cause the definition to be removedfrom the system.

    All #ifdef statements would evaluate to false.

    We can have the compiler skip over certain part of

    a source code by inserting commands like #ifdefand #endif.

  • 8/14/2019 C-Programming-Class 6

    16/49

    16

    Pseudo Code

  • 8/14/2019 C-Programming-Class 6

    17/49

    17

    #if, #else,# elifThe #if directive can be used to test whether an expression evaluates to

    a nonzero value or not.If the result of the expression is nonzero, then the subsequent lines upto a #else, #elif or #endif are compiled.

    main()

    {

    #if VALUE

  • 8/14/2019 C-Programming-Class 6

    18/49

    18

    Pseudo Codemain(){

    #if VALUE == 5

    statement 1;

    #elif

    statement 2;#elif

    statement 3;

    #else

    statement 4;

    #endif

    }

  • 8/14/2019 C-Programming-Class 6

    19/49

    19

    Stringizing Operator #

    The macro parameters in the strings that appear in the

    macro definitions are not recognized.

    To substitute a macro argument in a string constant, a

    special notation # in the macro body.

    When the # character precedes a parameter in the macro

    body, a string constant is replaced for both # and the

    parameter.

    The notation # is known as the Stringizing Operator.

  • 8/14/2019 C-Programming-Class 6

    20/49

    20

    An Example: #

    #define STRING(x,y) #xdeveloped by#y

    main()

    {

    char s[]=STRING(PROGRAM,ARUN);

    printf(%s\n,s);

    }

    Output:

    PROGRAM developed by ARUN

  • 8/14/2019 C-Programming-Class 6

    21/49

    21

    Token Pasting Operator:##

    A notation ## used in a macro definition

    concatenates the two tokens on either side of the

    symbol ## into one token.

    If the concatenation results in an invalid token, theresult is undefined.

    The notation ## is called as Token Pasting

    Operator.

  • 8/14/2019 C-Programming-Class 6

    22/49

    22

    An Example: ##

    #define DECIMAL(x) 3.##x

    main()

    {

    printf(%f\n,DECIMAL(14));

    }

    Output:

    3.140000

  • 8/14/2019 C-Programming-Class 6

    23/49

    23

    Advantages of Preprocessors

    A preprocessor improves the readability of

    programs.

    If facilitates easier modifications.It helps in writing portable programs.

    It enables easier debugging.

    It enables testing a part of a program.It helps in developing generalized program.

  • 8/14/2019 C-Programming-Class 6

    24/49

    24

    Variable Length Argument List

    When a programmer does not know how many arguments

    are there in a function, then this crisis can be solved using

    the concept of Variable Length Argument lists.

    The printf() function works on this concept.

    The function header could look like this

    int average(int x,)

    It tells the compiler to

    accept variable

    number of arguments.Ellipsis

  • 8/14/2019 C-Programming-Class 6

    25/49

    25

    Macros used in VLAL

    va_start() Initializes the list

    va_arg() Returns the next argument in the list

    va_end() Cleans up the argument list

    va_list() Variable should be declared of type

    va_list.

    Example: va_list a_list;

  • 8/14/2019 C-Programming-Class 6

    26/49

    26

    An Example:VLAL#include

    #include

    double average(int num,) {

    va_list arguments;

    double sum=0;int x;

    va_start(arguments,num);

    for(x=0;x

  • 8/14/2019 C-Programming-Class 6

    27/49

    27

    Dynamic Memory Allocation

    Dynamic memory allocation is the process ofallocating memory space during rum time.

    It is a unique feature in C.It allows us to create variables of various datatypes and structures of any size and lengthwhenever we require during execution time.

    In situations, where there is an unpredictablestorage requirement, this technique is very useful.

  • 8/14/2019 C-Programming-Class 6

    28/49

    28

    Static Memory Allocation

    The memory space allocated during compilationtime is called as Static Memory Allocation.

    The allocated memory space cannot be expanded

    to accommodate more data or cannot be reducedto accommodate less data.

    The memory space allocated is fixed and wecannot alter the size of the allocated space any

    time during execution. Example: int a[10];

  • 8/14/2019 C-Programming-Class 6

    29/49

    29

    Memory Map of a C Program

    BIOS

    C Program

    Global/Static

    Variables

    .

    Free Memory

    .

    AutomaticVariables

    ROM

    RAM

    Heap Memory

    Stack

  • 8/14/2019 C-Programming-Class 6

    30/49

    30

    malloc()

    The function allocates and reserves a block of

    memory,specified in bytes and returns a pointer to

    the first byte of allocated space.

    It reserves a block of memory by allocating

    specified number of bytes from the availability

    list(i.e from heap).

    It allocates a block of contiguous bytes.

  • 8/14/2019 C-Programming-Class 6

    31/49

    31

    malloc():Syntax

    ptr = (data_type*)malloc(size);

    ptr is a pointervariable of type

    data_type

    data_type can be anyof the basic data type

    or user defined data

    type

    size is the number of

    bytes required

  • 8/14/2019 C-Programming-Class 6

    32/49

    32

    malloc():Return Value

    On success,malloc() returns a pointer of type void

    to the newly allocated block memory.

    By typecasting appropriately it can be used tostore the data appropriately.

    If the specified size of memory is not available,

    the function returns a NULL.

  • 8/14/2019 C-Programming-Class 6

    33/49

    33

    malloc():An Example

    void main()

    {

    char *str;

    if(str=(char *)malloc(10)==NULL)

    {

    printf(Out of memory\n);

    exit(1);

    }

    strcpy( str,Hello);

    printf(String is %s\n,str);

    free(str);

    }

  • 8/14/2019 C-Programming-Class 6

    34/49

    34

    calloc()

    The function allocates multiple blocks of

    same size,initializes all locations to zero

    and returns a pointer to the first byte of theallocated space.

    It allocates a block of contiguous bytes.

  • 8/14/2019 C-Programming-Class 6

    35/49

    35

    calloc():Syntax

    ptr = (data_type*)calloc(n,size);

    ptr is a pointervariable of type

    data_type

    data_type can be anyof the basic data type

    or user defined data

    type

    size is the number

    of bytes requiredn is the numberof blocks to be

    allocated ifsize

    bytes

  • 8/14/2019 C-Programming-Class 6

    36/49

    36

    calloc():Return Value

    It returns a pointer to the newly allocatedblock.

    The total number of bytes allocated is equalto n*size and each location in the allocatedmemory is initialized to zero.

    If the specified size of memory is notavailable, the function returns a NULL.

  • 8/14/2019 C-Programming-Class 6

    37/49

    37

    calloc():An Examplevoid main()

    {

    char *str = NULL;

    str=(char *)calloc(10,sizeof(char));

    if(str==NULL)

    {

    printf(Out of memory\n);

    exit(1);

    }

    strcpy( str,Hello);

    printf(String is %s\n,str);

    free(str); }

  • 8/14/2019 C-Programming-Class 6

    38/49

    38

    realloc()

    This function is used to alter the size of the previously allocated space which is allocatedeither by using malloc orcalloc functions.

    This function guarantees that reallocating thememory will not destroy the original contents ofmemory.

    The contents of the old block will be copied into anewly allocated space and so,this functionguarantees that the earlier contents are not lost.

  • 8/14/2019 C-Programming-Class 6

    39/49

    39

    realloc():Syntax

    ptr = (data_type*)realloc(ptr,size);

    The address of the

    newly allocated

    memory after

    reallocation

    data_type can be anyof the basic data type

    or user defined data

    type

    size is thenumber of bytes

    required for

    reallocation

    Starting addressof allocated

    memory obtained

    previously

  • 8/14/2019 C-Programming-Class 6

    40/49

    40

    realloc():Return Value

    On success,the function returns the addressof reallocated block of memory.

    The address returned may be different fromthe original address.

    If reallocation fails or if size specified iszero,the function return NULL and theoriginal block is freed.

  • 8/14/2019 C-Programming-Class 6

    41/49

    41

    realloc():An Examplevoid main(){

    char *str;

    str=(char *)malloc(10);

    strcpy( str,Embedded);

    printf(Address of String %s is %d\n,str,str);

    str=(char *)realloc(str,40);

    strcpy( str,System Design);

    printf(Address of String %s is %d\n,str,str);

    free(str);

    }

  • 8/14/2019 C-Programming-Class 6

    42/49

    42

    free()

    This function is used to release the memory space

    that has been allocated earlier.

    This function de-allocates the allocated block ofmemory which is allocated by using the functions

    malloc,calloc and realloc.

    It is the responsibility of the programmer to de-

    allocate memory whenever it is not require by theapplication.

  • 8/14/2019 C-Programming-Class 6

    43/49

    43

    free():Syntax and Return Value

    free(ptr);

    ptr is a pointer to a

    memory block whichhas already been

    created

    There is no return value for the

    free() function.

  • 8/14/2019 C-Programming-Class 6

    44/49

    44

    Differences:malloc() & calloc()

    The syntax of malloc is

    ptr=(data_type*)malloc(size);

    Allocates a contiguous block of

    memory of specified size.Allocated space will not be

    initialized.

    Time efficiency is higher than

    calloc().

    The syntax of calloc is

    ptr=(data_type*)calloc(n,size);

    Allocates multiple blocks of

    memory,each block with thesame size.

    Each byte of allocated space is

    initialized to zero.

    It is more expensive in time

    efficiency because of zeroinitialization.

    malloc() calloc()

  • 8/14/2019 C-Programming-Class 6

    45/49

    45

    Memory Leakage

    main()

    {

    int a;

    a=(int*)malloc(sizeof(int));

    *a=10;

    a=(int*)malloc(sizeof(int));

    *a=20;

    }

    10

    20

    Allocation of memory is done twice.In this case, a contains the

    address of the most recently allocated memory.

    The earlier allocated memory remains inaccessable.

    The problem where in memory is reserved but not accessible to any

    application is called MEMORY LEAKAGE.

  • 8/14/2019 C-Programming-Class 6

    46/49

    46

    Dangling Pointer

    main()

    {

    int *a;

    a=(int*)malloc(sizeof(a));

    *a=20;

    free(a);

    ;

    ;}

    20

    ?

  • 8/14/2019 C-Programming-Class 6

    47/49

  • 8/14/2019 C-Programming-Class 6

    48/49

    48

    Summary

    A preprocessor is a facility provided for writingportable programs, easier program modificationsand easier debugging.

    A preprocessor processes the source codeprogram before it passes through the compiler.

    A macro is a simple function having its ownsyntax using #define,

    Dynamic memory allocation is the process ofallocating memory space during run time.

  • 8/14/2019 C-Programming-Class 6

    49/49

    Thank You!