The Standard C Library - Computer Action Team

1y ago
3.21 MB
54 Pages
Last View : 9d ago
Last Download : 6m ago
Upload by : Raelyn Goode

The Standard C Library1

The C Standard Library2

The C Standard LibraryI/O stdio.hprintf, scanf, puts, gets, open, close, read, write,fprintf, fscanf, fseek, Memory and string operationsstring.hmemcpy, memcmp, memset,strlen, strncpy, strncat, strncmp,strtod, strtol, strtoul, Character Testing ctype.hisalpha, isdigit, isupper,tolower, toupper, Argument Processingstdarg.hva list, va start, va arg, va end, 3

The C Standard LibraryUtility functionsstdlib.hrand, srand, exit, system, getenv,malloc, free, atoi, Timetime.hclock, time, gettimeofday, Jumpssetjmp.hsetjmp, longjmp, Processesunistd.hfork, execve, Signals signals.hsignal, raise, wait, waitpid, Implementation-defined constants limits.h, float.hINT MAX, INT MIN, DBL MAX, DBL MIN, 4

Formatted Outputint printf(char *format, )Sends output to standard outputint fprintf(FILE *stream, char *format, );Sends output to a fileint sprintf(char *str, char *format, )Sends output to a string variableReturn Value: The number of characters printed(not including trailing \0)On Error: A negative value is returned.5

Formatted OutputThe format string is copied as-is to output.Except the % character signals a formatting action.Format directives specificationsCharacter (%c), String (%s), Integer (%d), Float (%f)Fetches the next argument to get the valueFormatting commands for padding or truncating output and forleft/right justification%10s ! Pad short string to 10 characters, right justified%-10s ! Pad short string to 10 characters, left justified%.10s ! Truncate long strings after 10 characters%10.15s ! Pad to 10, but truncate after 15, right justifiedFor more details:man 3 printf6

Formatted Output#include stdio.h int main() {char *p;float f;p "This is a test”;f 909.2153258;printf(":%10.15s:\n", p);printf(":%15.10s:\n", p);printf(":%0.2f:\n", f);printf(":%15.5f:\n", f);}return 0;////////right justified,right justified,Cut off anythingCut off anythingtruncate to 15, pad to 10truncate to 10, pad to 15after 2nd decimal, no padafter 5th decimal, pad to 15OUTPUT:% test printf example:This is a test::This is a ::909.22::909.21533:%7

Formatted Inputint scanf(char *format, )Read formatted input from standard inputint fscanf(FILE *stream, const char *format, .);Read formatted input from a fileint sscanf(char *str, char *format, )Read formatted input from a stringReturn value: Number of input items assigned.Note that the arguments are pointers!8

Example: scanf#include stdio.h int main(){int x;scanf("%d", &x);printf("%d\n", x);}Why are pointers given to scanf?9

Example: scanf#include stdio.h int main(){long x;scanf("%ld", &x);printf("%ld\n", x);}Why are pointers given to scanf?10

Input Error Checking#include stdio.h #include stdlib.h int main() {int a, b, c;printf("Enter the first value: ");if (scanf("%d",&a) 0) {perror("Input error\n");exit(255);}printf("Enter the second value: ");if (scanf("%d",&b) 0) {perror("Input error\n");exit(255);}c a b;printf("%d %d %d\n", a, b, c);return 0;OUTPUT:}% test scanf exampleEnter the first value: 20Enter the second value: 3020 30 50%11

Line-Based I/Oint puts(char *line)Outputs string pointed to by line followed by newline character tostdoutchar *gets(char *s)Reads the next input line from stdin into buffer pointed to by sNull terminateschar *fgets(char *s, int size, FILE * stream)“size” is the size of the buffer.Stops reading before buffer overrun.Will store the \n, if it was getchar()Reads a character from stdinReturns it as an int (0.255)Returns EOF (i.e., -1) if “end-of-file” or “error”.12

General I/O13

Error handlingStandard error (stderr)Used by programs to signal error conditionsBy default, stderr is sent to displayMust redirect explicitly even if stdout sent to filefprintf(stderr, “getline: error on input\n”);perror(“getline: error on input”);Typically used in conjunction with errno return error codeerrno single global variable in all C programsInteger that specifies the type of errorEach call has its own mappings of errno to causeUsed with perror to signal which error occurred14

Example#include stdio.h #include fcntl.h #define BUFSIZE 16int main(int argc, char* argv[]) {int fd,n;char buf[BUFSIZE];}if ((fd open(argv[1], O RDONLY)) -1)perror("cp: can't open file");do {if ((n read(fd, buf, BUFSIZE)) 0)if (write(1, buf, n) ! n)perror("cp: write error to stdout");} while(n BUFSIZE);return 0;% cat opentest.txtThis is a test of CS 201and the open(), read(),and write() calls.% ./opentest opentest.txtThis is a test of CS 201and the open(), read(),and write() calls.% ./opentest asdfasdfcp: can't open file: No such file or directory%15

I/O Redirection in the Shell16

I/O via “File” Interface17

I/O via “File” Interface#include stdio.h #include string.h main (int argc, char** argv) {char *p argv[1];FILE *fp;}fp fopen ("tmpfile.txt","w ");fwrite (p, strlen(p), 1, fp);fclose (fp);return 0;OUTPUT:% test file ops HELLO% cat tmpfile.txtHELLO%18

Memory allocation and management(void *) malloc (int numberOfBytes)Dynamically allocates memory from the heapMemory persists between function invocations (unlike local variables)Returns a pointer to a block of at least numberOfBytes bytesNot zero filled!Allocate an integerint* iptr (int*) malloc(sizeof(int));Allocate a structurestruct name* nameptr (struct name*) malloc(sizeof(struct name));Allocate an integer array with “n” elementsint *ptr (int *) malloc(n * sizeof(int));19

Memory allocation and management(void *) malloc (int numberOfBytes)Be careful to allocate enough memory!Overrun on the space is undefined!!!Common error:char *cp (char *) malloc(strlen(buf)*sizeof(char))NOTE: strlen doesn’t account for the NULL terminator!Fix:char *cp (char *) malloc((strlen(buf) 1)*sizeof(char))20

Memory allocation and managementvoid free(void * p)Deallocates memory in heap.Pass in a pointer that was returned by malloc.Exampleint* iptr (int*) malloc(sizeof(int));free(iptr);Examplestruct table* tp (struct table*) malloc(sizeof(struct table));free(tp);Freeing the same memory block twice corrupts memoryand leads to exploits!21

Memory allocation and managementSometimes, before you use memory returned bymalloc, you want to zero itOr maybe set it to a specific valuememset() sets a chunk of memory to a specific valuevoid *memset(void *s, int ch, int n);Set this memory to this value for this number of bytes22

Memory allocation and managementHow to move a block of bytes efficiently?void *memmove(void *dest, void *src, int n);How to allocate zero-filled chunk of memory?void *calloc(int numberThings, int sizeOfThings);Note:These slides use “int”However, “size t” is better.Makes code more portable.“size t” ! unsigned integer.23

StringsString functions are provided in the string library.#include string.h Includes functions such as:Compute length of stringCopy stringsConcatenate strings 24

Stringschar *p "This is a test";pT h i si sat e s t \0char name[4] "Bob";char title[10] "Mr.";nametitle'B' 'o' 'b''M' 'r' '.' \0\0xxxxxx25

Copying stringsp:PPPPPPPq:0x100QQQQQQQ0x20026

Copying stringsp:PPPPPPPq:0x100QQQQQQQ0x20027

Copying 0QQQQQQQ0x20028

Copying 0QQQQQQQ0x20029


C String Library31

String code exampleOUTPUT:12, "Harry Porter"032

strncpy and null terminationOUTPUT:% ./a.out01234567k brown fox33

Other string functionsConverting strings to numbers#include stdlib.h long strtol (char *ptr, char **endptr, int base);long long strtoll (char *ptr, char **endptr, int base);Takes a character string and converts it to a long (long) integer.White space and or - are OK.Starts at beginning of ptr and continues until something nonconvertible is encountered.Examples:endptr (if not null, giveslocation of whereparsing stoppeddue to error)String"157""-1.6"" 50x""twelve""x506"Value returned157-1500034

Other string functionsdouble strtod (char * str, char **endptr);String to floating pointHandles digits 0-9.A decimal point.An exponent indicator (e or E).If no characters are convertible a 0 is returned.Examples:String"12""-0.123""123E 3""123.1e-5"Value returned12.000000-0.123000123000.0000000.00123135

Examples/* strtol Converts an ASCII string to its integerequivalent; for example, converts "-23.5" to -23. */int my value;char my string[] "-23.5";my value strtol(my string, NULL, 10);printf("%d\n", my value);36

Random number generation37

Random number generation#include stdio.h int main(int argc, char** argv) {int i,seed;}seed atoi(argv[1]);srand(seed);for (i 0; i 10; i )printf("%d : %d\n", i , rand());OUTPUT:%0123456789%./myrand 30: 493850533: 1867792571: 1191308030: 1240413721: 2134708252: 1278462954: 1717909034: 1758326472: 1352639282: 108137309938

MakefilesThe make utility: Compile things as necessary:makeThe makefile: Recipe for compiling your code.Call it makefile or Makefile (big or little M)The “make” utility will use that by defaultYou only have to specify the name if it’s called something elseThe first rule in the makefile is used by default if youjust say “make” with no argumentsThe second line of each rule (the command) must startwith a tab, not spaces!39

A simple Makefile% makegcc -Wall -g sd.c -o sd%40

A little more complex41

A more complex makefileCC gccCFLAGS -Wall -O2LIBS -lmOBJS driver.o kernels.o fcyc.o clock.oall: driverdriver: (OBJS) config.h defs.h fcyc.h (CC) (CFLAGS) (OBJS) (LIBS) -o driverdriver.o: driver.c defs.hkernels.o: kernels.cdefs.hfcyc.o: fcyc.c fcyc.hclock.o: clock.c42

How to make a tar file:43

GDB debugger

The Unix/Linux Debugger: gdbWhen all else fails Stoptheprogram Lookat(ormodify)registers Lookat(ormodify)memory Single- ‐steptheprogram Seta“breakpoint”To compile a program for use with gdb use the ‘-g’ compiler switch45

Controlling program executionrunStart the program.stepStep program until it reaches a different source line.nextStep program, proceeding through subroutine calls.Single step to the next source line, not into the call.Execute the whole routine at once; stop upon RETURN.continueContinue program execution after signal or breakpoint.46

Controlling program execution47

Printing out code and dataprintprint expr(gdb) print x(gdb) print argv[0]print {type} addr(gdb) p {char *} 0xbfffdce4(gdb) print/x addr‘/x’ says to print in hex. See “help x” for more formatsSame as examine memory address command (x)printf “format string” arg-list(gdb) printf "%s\n", argv[0]listDisplay source code48

Other Useful Commands49

Example de stdio.h void sub(int i) {char here [900];sprintf ((char *) here, "Function %s in %s", FUNCTION , FILE );printf ("%s @ line %d\n", here, LINE );}void sub2(int j) {printf ("%d\n”, j);}int main(int argc, char** argv){int x;x 30;sub2 (x);x 90;sub2 (x);sub (3);printf ("%s %d\n", argv[0], argc);return (0);}50

Walkthrough example% gcc% db)(gdb)(gdb)(gdb)(gdb)(gdb)(gdb)(gdb)(gdb)(gdb)-g gdb example.c -o b examplegdb exampleset args a b c dset program argumentslist 1,99list source file through line 99break mainset breakpoint at beginning of “main” functionbreak subset another breakpointbreak 6set break at source linerunstart program (breaks at line 16)disass mainshow assembly code for “main” functioninfo rdisplay register contentsp argvhex address of argv (char**)p argv[0]prints “gdb example”p argv[1]prints “a”p strlen(argv[1])prints 1p argcprints 5p /x argcprints 0x5p xuninitialized variable, prints some #nexecute to the next linep xx is now 30p/x &xprint address of xx/w &xprint contents at address of x51

Walkthrough b)(gdb)nsscontinuewherep xupp xdel 3continuego to next line (execute entire call)go to next source instrgo to next source instr (follow call)go until next breakpoint (breaks at line 6 in sub)list stack tracex no longer scopedchange scopex in scope, prints 90delete )info brdel 1break mainrunwatch xcquitget breakpointsdelete breakpointbreakpoint mainstart programset a data write watchpointwatchpoint triggeredquit52

Different gdb interfaces53


Printing out code and data print print expr (gdb) print x (gdb) print argv[0] print {type} addr (gdb) p {char *} 0xbfffdce4 (gdb) print/x addr '/x' says to print in hex. See "help x" for more formats Same as examine memory address command (x) printf "format string" arg-list (gdb) printf "%s\n", argv[0] list Display source code

Related Documents:

May 02, 2018 · D. Program Evaluation ͟The organization has provided a description of the framework for how each program will be evaluated. The framework should include all the elements below: ͟The evaluation methods are cost-effective for the organization ͟Quantitative and qualitative data is being collected (at Basics tier, data collection must have begun)

Silat is a combative art of self-defense and survival rooted from Matay archipelago. It was traced at thé early of Langkasuka Kingdom (2nd century CE) till thé reign of Melaka (Malaysia) Sultanate era (13th century). Silat has now evolved to become part of social culture and tradition with thé appearance of a fine physical and spiritual .

On an exceptional basis, Member States may request UNESCO to provide thé candidates with access to thé platform so they can complète thé form by themselves. Thèse requests must be addressed to esd rize unesco. or by 15 A ril 2021 UNESCO will provide thé nomineewith accessto thé platform via their émail address.

̶The leading indicator of employee engagement is based on the quality of the relationship between employee and supervisor Empower your managers! ̶Help them understand the impact on the organization ̶Share important changes, plan options, tasks, and deadlines ̶Provide key messages and talking points ̶Prepare them to answer employee questions

Dr. Sunita Bharatwal** Dr. Pawan Garga*** Abstract Customer satisfaction is derived from thè functionalities and values, a product or Service can provide. The current study aims to segregate thè dimensions of ordine Service quality and gather insights on its impact on web shopping. The trends of purchases have

Chính Văn.- Còn đức Thế tôn thì tuệ giác cực kỳ trong sạch 8: hiện hành bất nhị 9, đạt đến vô tướng 10, đứng vào chỗ đứng của các đức Thế tôn 11, thể hiện tính bình đẳng của các Ngài, đến chỗ không còn chướng ngại 12, giáo pháp không thể khuynh đảo, tâm thức không bị cản trở, cái được

Le genou de Lucy. Odile Jacob. 1999. Coppens Y. Pré-textes. L’homme préhistorique en morceaux. Eds Odile Jacob. 2011. Costentin J., Delaveau P. Café, thé, chocolat, les bons effets sur le cerveau et pour le corps. Editions Odile Jacob. 2010. Crawford M., Marsh D. The driving force : food in human evolution and the future.

Le genou de Lucy. Odile Jacob. 1999. Coppens Y. Pré-textes. L’homme préhistorique en morceaux. Eds Odile Jacob. 2011. Costentin J., Delaveau P. Café, thé, chocolat, les bons effets sur le cerveau et pour le corps. Editions Odile Jacob. 2010. 3 Crawford M., Marsh D. The driving force : food in human evolution and the future.