Documentos de Académico
Documentos de Profesional
Documentos de Cultura
preamble to the storage classes ! scope ! linkage ! storage duration memory management functions
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)
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
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
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
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
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
ece220, UofA
31
ece220, UofA
32
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-class specifiers
C has five keywords that can be grouped as storageclass specifiers: ! auto ! register ! static ! extern ! typedef
ece220, UofA
36
ece220, UofA
37
ece220, UofA
38
ece220, UofA
40
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
- ptr must always point to the same location and the value stored at the location must not change
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
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