storage classes, linkage & memory management

29
C Programming Language & Data Structure Prepared by: Mo’meN M. Ali E-mail: [email protected]

Upload: momen-m-ali

Post on 13-Aug-2015

85 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Storage classes, linkage & memory management

CProgramming Language

&Data Structure

Prepared by: Mo’meN M. AliE-mail: [email protected]

Page 2: Storage classes, linkage & memory management

References

• www.stackoverflow.com

• C Primer Plus 6th Edition

• Let Us C 5th Edition

• The C Programming Language 2nd Edition

• C Modern Approach 2nd Edition

• Data Structures and Algorithm Analysis in C 2nd Edition

C Programming LanguageMo’meN M. Ali

Page 3: Storage classes, linkage & memory management

Review Programs are uploaded to this Git repo

https://github.com/Mo2meN-Ali/x86/tree/master/Programming%20Course/3-%20Storage%2C%20Linkage%20%26%20memory%20management

C Programming LanguageMo’meN M. Ali

Page 4: Storage classes, linkage & memory management

Topics • Arrays & Pointers.

• Character String & String Functions.

• Storage Classes, Linkage & Memory Management.

• File Input/Output.

• Structures & Other Data Formats.

• Bit Fiddling.

• The C Preprocessor & The C Library.

• Algorithm Analysis & ADT.

• Stacks & Queues.

• Trees.

C Programming LanguageMo’meN M. Ali

Page 5: Storage classes, linkage & memory management

Today You Will Learn About:

• Keywords:auto, extern, static, register, const, volatile, restricted.

• Functions:rand(), srand(), time(), malloc(), calloc(), free().

• Designing more complex programs: Multi-file programs.

C Programming LanguageMo’meN M. Ali

Page 6: Storage classes, linkage & memory management

Scope• C variable Scopes:

1. File scope.2. Function prototype scope.3. Function scope.4. Block scope.

• So, what is a block in the C Literature ? A block in C is anything that between parenthesis:Some_function(){ // That’s a function scope

{ // a new block, which would have a different scope…..

} // End of the Block scope} // End of the function scope

C Programming LanguageMo’meN M. Ali

Page 7: Storage classes, linkage & memory management

Linkage• C object Linkages:

1. External Linkage: can be used anywhere in the code (typically a multifileprogram).

2. Internal Linkage: can be used ONLY in a single translation unit (.c + .h files).3. No Linkage: can not be used nor exists outside of its block or function.

• Variables with block scope, function scope, or function prototype scope have nolinkage. (block/function scope)

• Variables preceded with the keyword static have internal linkage. (file scope)

• Variables defined outside any block (global variables) have external linkage.(program scope)

C Programming LanguageMo’meN M. Ali

Page 8: Storage classes, linkage & memory management

Storage Duraction• C object Storage durations:

1. Automatic storage duration.2. Static storage duration.3. Allocated storage duration.

C Programming LanguageMo’meN M. Ali

Page 9: Storage classes, linkage & memory management

Automatic storage Duration1. Variables with memory allocated for it only when the program enters the block in which they are defined and the memory is freed when the block is exited.

2. Block/function scope variables has automatic scope duration.3. Also called local variables.

int try(void)

{ // memory allocated for the first x.x;

{ // memory allocated for the second x (this one is different from the // previous one with a different memory address)x;

} // The second x is deleted from the program and the memory.

return x; // This will return the first x which the only one remaining.}

C Programming LanguageMo’meN M. Ali

• Review Program: automatic storage duration• Review Program: automatic storage class (C99)

Page 10: Storage classes, linkage & memory management

Static storage Duration1. It means that The variable exists throughout the program execution until.

2. Both file scope and program scope variables have a static storage duration.

3. Block/function scope variables can have a static storage duration by preceding them with the keyword static .

4. Static variables are initialized to 0 by default.

C Programming LanguageMo’meN M. Ali

Note:• For program scope, file scope variables and functions(), the keyword static ONLY

effect the linkage type not the storage duration.

Page 11: Storage classes, linkage & memory management

Static variables within block scope

1. Variables with block scope and static duration which means it exists throughout the program not to be deleted when the end of the block is reached.

2. Those variables still has no linkage.

C Programming LanguageMo’meN M. Ali

• Review Program: static variables within block

Page 12: Storage classes, linkage & memory management

Static variables with external linkage1. External variables has file scope, external linkage and static storage duration.2. External variables are declared outside all blocks.3. If an external variable is defined in one source file and is to be used in another source code within the same program we must declare it in the other file using the keyword: extern.

4. An external variable can additionally be declared inside a function or a block preceded by the keyword: extern as a matter of documentation ONLY.

int Errupt; /* externally defined variable */double Up[100]; /* externally defined array */extern char Coal; /* mandatory declaration if Coal defined in another file */void next(void);int main(void){extern int Errupt; /* optional declaration */extern double Up[]; /* optional declaration */

C Programming LanguageMo’meN M. Ali

Page 13: Storage classes, linkage & memory management

Register variables

1. Register variables can be with luck stored in the CPU register rather than the memory.

2. You can’t take the address of a register variable.3. In most other cases a register variable are the same as automatic variables.

C Programming LanguageMo’meN M. Ali

Page 14: Storage classes, linkage & memory management

Multiple Files Programs

1. It’s program that more than one translation unit (.c + .h) we also call it module .2. we write programs that way in order to break a big problem into several small modules each module is fixing an atomic part of the problem.

3. Internal linkage and external linkage only matters in multiple translation units programs.

C Programming LanguageMo’meN M. Ali

• Review Program: multifile program

Page 15: Storage classes, linkage & memory management

Storage classes and functions

• A function can either be external, static or inline (C99) 1. External functions is the regular functions which can be used anywhere in

the program.2. Static functions can only be used within the defining file.

• The functions gamma() and delta() can be used by functions in other files that are partof the program, but beta() cannot. Because this beta() is restricted to one file.

double gamma(double); /* external by default */static double beta(int, int);extern double delta(double, int);

C Programming LanguageMo’meN M. Ali

Page 16: Storage classes, linkage & memory management

Exercise 3.0

45 Minutes

MO’MEN M. ALI

C Programming Language

Page 17: Storage classes, linkage & memory management

Memory Allocation: malloc(), free()

• All objects we are using must be allocated.• Automatic allocation for variables, functions is the default in any compiler, however, we can allocate things ourselves manually which gives us better control over the program.• Manual allocation have the advantage of run-time allocation which enhances the memory usage.

C Programming LanguageMo’meN M. Ali

Page 18: Storage classes, linkage & memory management

malloc()

(*some-type) malloc(SIZE * No.of blockes);

• It takes the whole memory block size to be allocated which always is the size of one element (unit) multiplied by the number of elements (units).• It returns a pointer-to-void which points to the first address of the allocated block (which should be casted to the address of the destination object), in case of failure it returns NULL pointer.

double *ptd; // malloc return value is an addressptd = (double *) malloc(n * sizeof (double)); /* this will produce an array of n

elements each of which is double*/

• Now we can use ptd[n]; // Array of doubleC Programming LanguageMo’meN M. Ali

Page 19: Storage classes, linkage & memory management

free()

• free(pointer-to-the-allocated-block)

• After we are done using the memory allocated we need to release the memory or in other words free it.

free(ptd); // now the memory that has been used by ptd is once again free• Now ptd is just a pointer-to-double which is empty.

C Programming LanguageMo’meN M. Ali

• Review Program: Array Memory Allocation

Page 20: Storage classes, linkage & memory management

calloc()(*some-type) calloc(SIZE * No.of blockes);

• It takes the whole memory block size to be allocated which always is the size of one element (unit) multiplied by the number of elements (units).• It returns a pointer-to-void which points to the first address of the allocated block (which should be casted to the address of the destination object), in case of failure it returns NULL pointer.• It sets all the bits of the allocated block to zero.

long *newmem; // malloc return value is an address

newmem = (long *)calloc(100, sizeof (long)); /* this will produce an array of n elements each of which is double*/

• Now we can use newmem[100]; // Array of long

C Programming LanguageMo’meN M. Ali

Page 21: Storage classes, linkage & memory management

Dynamic Memory Allocationg and VLAsint vlamal(){

int n;int *pi;

scanf("%d", &n); // The size of the array is defined at run-time which// only can be done under the support of the C99

pi = (int *) malloc (n * sizeof (int));int ar[n]; // vlapi[2] = ar[2] = -5;...

}

C Programming LanguageMo’meN M. Ali

Page 22: Storage classes, linkage & memory management

Some Conventions

int n = 5;int m = 6;int ar2[n][m]; // n x m VLAint (* p2)[6]; // works pre-C99int (* p3)[m]; // requires VLA supportp2 = (int (*)[6]) malloc(n * 6 * sizeof(int)); // n * 6 arrayp3 = (int (*)[m]) malloc(n * m * sizeof(int)); // n * m array

// above expression also requires VLA supportar2[1][2] = p2[1][2] = 12

C Programming LanguageMo’meN M. Ali

Page 23: Storage classes, linkage & memory management

Memory Layout of C Programs

1. Text or ELF segment2. Initialized data segment3. BSS or Uninitialized data segment4. Stack5. Heap

C Programming LanguageMo’meN M. Ali

• Review Program: Program Sections

Page 24: Storage classes, linkage & memory management

The const type qualifier

• The const keyword in a declaration establishes a variable whose value cannotbe modified by assignment or by incrementing or decrementing.

const int nochange; /* qualifies m as being constant */nochange = 12; /* not allowed */const int nochange = 12; /* ok */

C Programming LanguageMo’meN M. Ali

Page 25: Storage classes, linkage & memory management

Using const with pointers

• There’s two ways to use const with pointers:1. pointer-to-const: the pointed to data cannot be altered but the pointer itself

can be changed to point to something else.

const float *pf; /* pf points to a constant float value */

1. const pointer-to: the pointer itself cannot point to something else than the initial object which means it cannot be incremented or decremented but the data pointed to can be changed.

float *const pt; /* pt is a const pointer */

C Programming LanguageMo’meN M. Ali

Page 26: Storage classes, linkage & memory management

The volatile type qualifier

• The volatile qualifier tells the compiler that a variable can have its valuealtered by agencies other than the program. It is typically used for hardwareaddresses and for data shared with other programs or threads runningsimultaneously.

The syntax is the same as for const :volatile int loc1; /* loc1 is a volatile location */volatile int *ploc; /* ploc points to a volatile location */

C Programming LanguageMo’meN M. Ali

Page 27: Storage classes, linkage & memory management

The volatile type qualifier

• The restrict keyword enhances computational support by giving the compilerpermission to optimize certain kinds of code. It can be applied only to pointers,and it indicates that a pointer is the sole initial means of accessing a data object.

int ar[10];int *restrict restar = (int *) malloc(10 * sizeof (int));int *par = ar;

• Here, the pointer restar is the sole initial means of access to the memoryallocated by malloc() . Therefore, it can be qualified with the keyword restrict .The pointer par, however, is neither the initial nor the sole means of access tothe data in the ar array, so it cannot be qualified as restrict .

C Programming LanguageMo’meN M. Ali

Page 28: Storage classes, linkage & memory management

Random Number generation• Random number generation is most of the time are not a real random but

rather a predictable algorithm.

static unsigned long int next = 1; /* the seed */

int rand0(void){/* magic formula to generate pseudorandom number */

next = next * 1103515245 + 12345;return ( (unsigned int) (next/65536) % 32768 );

}

void srand1(unsigned int seed){

next = seed; // we can change the seed by using this function}

C Programming LanguageMo’meN M. Ali

• Review Program: rand driver

Page 29: Storage classes, linkage & memory management

THANK YOUSEE YOU SOON

EMBEDDED SYSTEMS WORKSHOPMo’meN M. Ali