Está en la página 1de 10

outline

storage classes and memory


ece220, UofA

preamble to the storage classes ! scope ! linkage ! storage duration memory management functions

ece220 programming for electrical engineering

ece220, UofA

scope
! the region or regions of a program that can access an identifier ! types of scope for a variable in C : ! block scope ! function prototype scope ! file scope ! function scope

block scope
is a region of code contained within an opening brace and the matching closing brace - for instance, the entire body of a function is a block scope
- any compound statement within a function - a variable defined inside a block has block scope - also, formal function parameters, have block scope - belong to the block containing the function body

ece220, UofA

ece220, UofA

program #1
double blocky(double cleo) { double patrick = 0.0; int i; for (i = 0; i < 10; i++) { double q = cleo * i; // start of scope for q// ... scope of q is limited to the inner block, patrick *= q; and only code within } // end of scope for q// that block can access q ... return patrick; }
cleo and patrick have block scope extending to the closing brace (outer block)

function prototype scope


applies to variable names used in function prototypes
int mighty(int mouse, double large); void use_a_VLA(int n, int m, ar[n][m]);

runs from the point the variable is defined to the end of the prototype declaration

ece220, UofA

ece220, UofA

file scope
a variable placed outside of any function has file scope it is visible from the point it is defined to the end of the file containing the definition

program #2
#include <stdio.h> int units = 0; /* a variable with file scope */ void critic(void); int main(void) variable units has file scope, and it can { be used in both main() and critic() ... since, used in more than one function, file } scope variables are also called global void critic(void) variables { ... }
7 ece220, UofA 8

ece220, UofA

function scope
it applies - only to labels used by goto statements (means a goto label in a particular function is visible to code) anywhere in that function, regardless of the block in which it appears - external linkage - internal linkage - no linkage

linkage
a C variable has one of the following linkages:

ece220, UofA

ece220, UofA

10

linkage
! variables with block scope or prototype scope have no linkage - they are private to the block or prototype in which they are defined ! variable with file scope can have either internal or external linkage - a variable with external linkage can be used anywhere in a multi-file program - a variable with internal linkage can be used anywhere in a single file
ece220, UofA 11

linkage
internal or external linkage of a file scope variable for a storage class specifier: static
int giants static int int main() { ... } ... = 5; //file scope, external linkage dodgers = 3; //file scope, internal linkage

the variable giants can be used by other files that are part of the same program the dodgers variable is private to this particular file, but can be used by any function in the file
12

ece220, UofA

storage duration
C variable has one of the following two storage durations: ! static storage duration ! automatic storage duration

storage duration:
static
! variables exist throughout program execution ! all file scope variables, using internal linkage or external linkage, have static storage duration note: for file scope variables, the keyword static indicates the linkage type, not the storage duration

ece220, UofA

13

ece220, UofA

14

storage duration:
automatic
! variables with block scope normally have automatic storage duration ! these variables have memory allocated for them when the program enters the block in which they are defined, the memory is freed when the block is exited; memory used for automatic variables is a workspace or scratch pad that can be reused ! for example, after a function call terminates, the memory it used for its variables can be used to hold variables for the next function that is called
ece220, UofA 15

storage classes
C uses scope, linkage, and storage duration to define five storage classes: ! automatic ! register ! static with block scope ! static with external linkage ! static with internal linkage

ece220, UofA

16

storage classes
storage class automatic register static with external linkage static with internal linkage static with no linkage duration automatic automatic static static static scope block block file file block linkage none none external internal none how declared in a block in a block with the keyword register outside of all functions outside of all functions with the keyword static in a block with the keyword static

automatic variables
! a variable belonging to the automatic storage class
- automatic storage duration - block scope - no linkage

! by default, any variable declared in a block or function header belongs to the automatic storage class ! declared explicitly by a keyword: auto
int main(void) { auto int plox;
17 ece220, UofA 18

ece220, UofA

automatic variables
variable i: visible only within the inner braces int loop(int n) compiler error if used before or after the inner { block int m; // m in scope scanf("%d", &m); { int i; // m and i in scope for (i = m; i < n; i++) puts("i is local to a sub-block\n"); } return m; // m in scope, i not } variables - n and m: defined in the function head and in the outer block; scope for the whole function and exist until the function terminates
ece220, UofA 19

automatic variables
/* hiding.c -- variables in blocks */ #include <stdio.h> int main() { int x = 30; /* original x */ printf("x in outer block: %d\n", x); { int x = 77; /* new x, hides first x */ printf("x in inner block: %d\n", x); } printf("x in outer block: %d\n", x); while (x++ < 33) /* original x */ { int x = 100; /* new x, hides first x */ x++; printf("x in while loop: %d\n", x); } printf("x in outer block: %d\n", x); return 0; } output: x in outer block: 30 x in inner block: 77 x in outer block: 30 x in while loop: 101 x in while loop: 101 x in while loop: 101

x in outer block: 34

ece220, UofA

20

register variables
!stored in the CPU registers or, more generally, in the fastest memory available !a ccessed and manipulated more rapidly than regular variables - for faster access !no address since stored in register, not in the in memory; it prevents us from taking the address of a register variable

register variables
! same as automatic variables, they have
- automatic storage duration - block scope - no linkage

! declared by using the storage class specifier: register


int main(void) { register int quick;
ece220, UofA 22

ece220, UofA

21

register variables
! declaring a variable as a register class is more a request than a direct order ! we can request that formal parameters be register variables we use the keyword in the function heading - void macho(register int n) ! the types that can be declared register may be restricted - for example, the registers in a processor might not be large enough to hold type double

static var & block scope


static specifier - when used in a declaration for a variable with block scope: ! gives the variable static storage duration ! ensures it exists and retains its value as long as the program is running, even at times the containing block is not in use ! block scope and no linkage are retained

ece220, UofA

23

ece220, UofA

24

program #3
#include <stdio.h> void trystat(void); int main(void) { int count; for (count = 1; count <= 3; count++) { printf("Here comes iteration %d:\n", count); trystat(); } return 0; } void trystat(void) { int fade = 1; static int stay = 1; printf("fade = %d and stay = %d\n", fade++, stay++); }
ece220, UofA

static var & external linkage


extern specifier: indicates that we are declaring a variable that has been defined elsewhere ! if the variable is defined in another file declaring the variable with extern is mandatory ! if the declaration containing extern has file scope, the variable referred to must have external linkage ! if the declaration containing extern has block scope, the referred-to variable can have either external linkage or internal linkage has file scope, external linkage, and static storage duration
25 ece220, UofA 26

Output: Here comes iteration 1: fade = 1 and stay = 1 Here comes iteration 2: fade = 1 and stay = 2 Here comes iteration 3: fade = 1 and stay = 3

program #4
int Errupt; double Up[100]; extern char Coal; void next(void); int main(void) { extern int Errupt; extern double Up[]; ... } void next(void) { ... }
ece220, UofA

initializing external variables


! like automatic variables, external variables can be initialized explicitly ! unlike automatic variables, external variables are automatically initialized to zero if we do not initialize them; this rule applies to elements of an externally defined array, too ! unlike the case for automatic variables, we can use only constant expressions to initialize file scope variables
27 ece220, UofA 28

/* externally defined variable */ /* externally defined array */ /* mandatory declaration */

/* optional declaration */ /* optional declaration */

initializing external variables


int x = 10; // ok, 10 is constant int y = 3 + 20; // ok, a constant expression size_t z = sizeof(int); // ok, a constant expression int x2 = 2 * x; // not ok, x is a variable

program #5
#include <stdio.h> int units = 0; /* an external variable */ void critic(void); int main(void) { extern int units; /* an optional redeclaration */ printf("How many pounds to a firkin of butter?\n"); scanf("%d", &units); while ( units != 56) critic(); printf("You must have looked it up!\n"); Output: return 0; How many pounds to a firkin of butter? } 14 void critic(void) No luck, chummy. Try again. { 56 /* optional redeclaration omitted */ You must have looked it up! printf("No luck, chummy. Try again.\n"); scanf("%d", &units); }
29 ece220, UofA 30

ece220, UofA

static var & internal linkage


! variables of this storage class have static storage duration, file scope, and internal linkage ! we create one by defining it outside of any function (just as with an external variable) with the storage class specifier: static
static int svil = 1; int main(void) { // static variable, //internal linkage

static var & internal linkage


! ordinary external variable can be used by functions in any file that is a part of the program ! but the static variable with internal linkage can be used only by functions in the same file ! we can re-declare any file scope variable within a function by using the storage class specifier: extern

ece220, UofA

31

ece220, UofA

32

static var & internal linkage


int traveler = 1; static int stayhome = 1; int main() { extern int traveler; extern int stayhome; ... // external linkage // internal linkage storage class automatic register // use global traveler // use global stayhome static with external linkage static with internal linkage static with no linkage duration automatic automatic static static static

storage classes
scope block block file file block linkage none none external internal none how declared in a block in a block with the keyword register outside of all functions outside of all functions with the keyword static in a block with the keyword static

both traveler and stayhome are global for this particular file, but only traveler can be used in other files declarations with extern main() is using the two global variables, but stayhome continues to have internal linkage

ece220, UofA

33

ece220, UofA

34

storage classes and functions


! functions, too, have storage classes ! can be either external (the default) or static ! an external function can be accessed by functions in other files ! whereas, a static function can be used only within the defining file
double gamma(); /* external by default */ static double beta(); extern double delta();s
ece220, UofA 35

storage-class specifiers
C has five keywords that can be grouped as storageclass specifiers: ! auto ! register ! static ! extern ! typedef

ece220, UofA

36

storage-class specifiers: auto


! indicates a variable with automatic storage duration ! used only in declarations of variables with block scope which already have automatic storage duration, so its main use is documenting intent

storage-class specifiers: register


! used only with variables of block scope ! it puts a variable into the register storage class ! amounts to a request that the variable be stored in a register for faster access ! prevents you from taking the address of the variable

ece220, UofA

37

ece220, UofA

38

storage-class specifiers: static


! used in a declaration for a variable with block scope ! gives static storage duration so a variable exists and retains its value as long as the program is running even at times the containing block is not in use ! variable retains block scope and no linkage ! used in a declaration with file scope, it indicates that the variable has internal linkage
ece220, UofA 39

storage-class specifiers: extern


! indicates that you are declaring a variable that has been defined elsewhere ! if the declaration containing extern has file scope, the variable referred to must have external linkage ! if the declaration containing extern has block scope, the referred-to variable can have either external linkage or internal linkage, depending on the defining declaration for that variable

ece220, UofA

40

storage-class specifiers: typedef


! does not say anything about memory storage, but it is thrown in for syntax reasons ! in particular, we can use no more than one storageclass specifier in a declaration, i.e., we cannot use one of the other storage-class specifiers as part of a typedef

malloc()
! allocate more memory as a program runs ! takes one argument: the number of bytes of memory we want ! malloc() finds a suitable block of free memory ! allocates memory but does not assign a name to it ! it returns the address of the first byte of that block ! we can assign that address to a pointer variable and use the pointer to access the memory

ece220, UofA

41

ece220, UofA

42

malloc()
! malloc() can be used to return pointers to arrays, structures, and so forth ! normally the return value is typecast to the proper value ! we should still typecast for clarity, but assigning a pointer-to void value to a pointer of another type is not considered a type clash ! if malloc() fails to find the required space, it returns the null pointer

malloc()
double * ptd; ptd = (double *) malloc(30 * sizeof(double));

this code requests space for 30 type double values and sets ptd to point to the location note: that ptd is declared as a pointer to a single double and not to a block of 30 double values

ece220, UofA

43

ece220, UofA

44

free()
! free() takes as its argument an address returned earlier by malloc() and frees up the memory that had been allocated ! the duration of allocated memory is from when malloc() is called to allocate the memory until free() is called to free up the memory so that it can be reused ! malloc() and free() are considered as managing a pool of memory

free()
! argument to free() should be a pointer to a block of memory allocated by malloc() ! we can not use free() to free memory allocated by other means, such as declaring an array ! both malloc() and free() have prototypes in the stdlib.h header file

ece220, UofA

45

ece220, UofA

46

program #6
#include <stdio.h> #include <stdlib.h> /* for malloc(), free() */ int main(void) { double * ptd; int max; int number; int i = 0; puts("What is the maximum number of type double entries?"); scanf("%d", &max); space to hold the requested number of entries and then ptd = (double *) malloc(max * sizeof (double)); assigns the address of the if (ptd == NULL) block to the pointer ptd { puts("Memory allocation failed. Goodbye."); exit(EXIT_FAILURE); malloc() can fail to procure the } desired amount of memory - in that case, the function returns the null p o i n t e r, a n d t h e p r o g r a m terminates
ece220, UofA 47

program #6
/* ptd now points to an array of max elements */ puts("Enter the values (q to quit):"); while (i < max && scanf("%lf", &ptd[i]) == 1) ++i; printf("Here are your %d entries:\n", number = i); for (i = 0; i < number; i++) Output: { What is the maximum number of entries? printf("%7.2f ", ptd[i]); 5 if (i % 7 == 6) putchar('\n'); Enter the values (q to quit): 20 30 35 25 40 80 } if (i % 7 != 0) Here are your 5 entries: putchar('\n'); 20.00 30.00 35.00 25.00 40.00 puts("Done."); Done. free(ptd); return 0; freed by calling the free() function }

ece220, UofA

48

calloc()
long * newmem; newmem = (long *)calloc(100, sizeof (long));
long uses 4 bytes, so this instruction sets up 100 4byte units, using 400 bytes in all for storage

type qualifiers
type qualifiers : ! const ! volatile ! restrict

! calloc() function has one more feature - it sets all the bits in the block to zero ! free() function can also be used to free memory allocated by calloc()
ece220, UofA 49 ece220, UofA 50

type qualifiers: const


! qualifies data as being constant ! when used with pointers, const can indicate that the pointer itself is constant, or that the data it points to is constant, depending on the placement of const in the declaration
const int days1[12] = {31,28,31,30,31,30,31,31,30,31,30,31};

type qualifiers: const


const float * pf; float * const pt; /* pf points to a constant float */ /* pt is a const pointer */

const float * const ptr;

- ptr must always point to the same location and the value stored at the location must not change

this creates an array of data that the program cannot alter


ece220, UofA 51 ece220, UofA 52

type qualifiers: const


float const * pfc;

type qualifiers: volatile


! indicates that data may be altered by processes other than the program ! its purpose is to warn the compiler to avoid optimizations that assume otherwise syntax is the same as for const:
volatile int loc1; //loc1 is a volatile location volatile int * ploc; //ploc points to a volatile location

the same as
const float * pfc; void display(const int array[], int limit);

the parameter declaration const int array[] is the same as const int * array, so the declaration says that the data to which array points cannot be changed
ece220, UofA 53

ece220, UofA

54

type qualifiers: restrict


! also provided for reasons of optimization ! a pointer with restrict is identified as providing the only access to a block of data
int ar[10]; int * restrict restar = (int *)malloc(10*sizeof(int)); int * par = ar; The compiler can replace the ... two statements involving for (n = 0; n < 10; n++) restar with a single statement { having the same effect restar[n] par[n] += 5; optimization restar[n] += 5; ar[n] *= 2; par[n] += 3; restar[n] += 3; }

summary
! memory used to store data in a program can be characterized by: ! storage duration ! scope ! linkage ! storage duration can be static, automatic, or allocated

+= 8;

55

ece220, UofA

56

summary:
storage duration
! static: memory is allocated at the start of program execution and persists as long as the program is running ! automatic: memory for a variable is allocated when program execution enters the block in which the variable is defined and is freed when the block is exited ! allocated: memory is allocated by calling malloc() (or a related function) and freed by calling the free() function
ece220, UofA 57

summary
! scope determines which parts of a program can access the data ! linkage describes the extent to which a variable defined in one unit of a program can be linked to elsewhere ! storage classes: automatic, register, static, no linkage, static, external linkage, static, internal linkage

ece220, UofA

58

summary
! memory allocation is preformed by using the malloc() (or related function), which returns a pointer to a block of memory having the requested number of bytes ! this memory can be released for reuse by calling the free() using the address as the argument ! the type qualifiers are const, volatile, and restrict

ece220, UofA

59

También podría gustarte