C Programming Basics GCC 8.2.0 & GDB 8.1.1 nike.cs.uga.edu - - PDF document

c programming
SMART_READER_LITE
LIVE PREVIEW

C Programming Basics GCC 8.2.0 & GDB 8.1.1 nike.cs.uga.edu - - PDF document

8/21/18 C Programming Basics GCC 8.2.0 & GDB 8.1.1 nike.cs.uga.edu brew macOS gcc-8 brew install gcc, or brew upgrade gcc Also need Xcode CLT xcode-select install Brew info gcc brew install gdb


slide-1
SLIDE 1

8/21/18 1

C Programming

Basics

GCC 8.2.0 & GDB 8.1.1

  • nike.cs.uga.edu
  • brew macOS gcc-8

– brew install gcc, or – brew upgrade gcc Also need Xcode CLT – xcode-select –install – Brew info gcc

  • brew install gdb
  • https://sourceware.org/gdb/wiki/BuildingOnDarwin
slide-2
SLIDE 2

8/21/18 2

Set up: LIBRARY : PATH

  • On nike.cs.uga.edu
  • LD_LIBRARY_PATH

– ~maria/usr/GDB-8.1.1/lib – ~maria/usr/GCC-8.2.0/lib64 – ~maria/usr/GCC-8.2.0/lib

  • PATH

– ~maria/usr/GCC-8.2.0/bin/gcc

.login (tcsh) or .profile (bash/ksh)

ls /home/profs/maria/usr/GCC-8.2.0/ ls /home/profs/maria/usr/GDB-8.1.1/ setenv GCC_HOME /home/profs/maria/usr/GCC-8.2.0/ setenv GDB_HOME /usr/profs/maria/usr/GDB-8.1.1/ setenv PATH ${GCC_HOME}/bin/:${PATH} setenv PATH ${GDB_HOME}/bin/:${PATH} setenv LD_LIBRARY_PATH ${GCC_HOME}/lib:${LD_LIBRARY_PATH} setenv LD_LIBRARY_PATH ${GCC_HOME}/lib64:${LD_LIBRARY_PATH} setenv LD_LIBRARY_PATH ${GDB_HOME}/lib:${LD_LIBRARY_PATH} export GCC_HOME=/home/profs/maria/usr/GCC-8.2.0/ export GDB_HOME=/usr/profs/maria/usr/GDB-8.1.1/ PATH= ${GCC_HOME}/bin/:${PATH} PATH =${GDB_HOME}/bin/:${PATH} export=LD_LIBRARY_PATH=${GCC_HOME}/lib:${LD_LIBRARY_PATH} export=LD_LIBRARY_PATH=${GCC_HOME}/lib64:${LD_LIBRARY_PATH} export=LD_LIBRARY_PATH=${GDB_HOME}/lib:${LD_LIBRARY_PATH}

csh/tcsh bash/ksh

slide-3
SLIDE 3

8/21/18 3

  • C Basics
  • Debugging Tools
  • C Standard Library

– getopt – stdio.h – stdlib.h – string.h

C Basics

  • For Some:

– Overlap of C++ System Programming.

  • Pointers, Arrays, structs, Casting
  • Memory Management
  • Function Pointers / Generic Types
  • Strings
slide-4
SLIDE 4

8/21/18 4

Scope of Variables

  • Global Variables:

– Declared outside functions

  • Seen by all files
  • Use extern to use a global variables

declared in another file

  • const Variables

– Data stored in read-only segment – (variable does not change)

  • static Variables

– In functions – value is persistent between invocations (not volatile). – Static Functions – not visible

  • utside object file (not same

semantic).

Carnegie Mellon

Variable Declarations & Qualifiers

Global Variables:

Defined outside functions, seen by all files

Use “extern” keyword to use a global variable defined in another file

Const Variables:

For variables that won’t change

Data stored in read-only data section

Static Variables:

For locals, keeps value between invocations

USE SPARINGLY

Note: static has a different meaning when referring to functions (not visible outside of

  • bject file)

https://www.geeksforgeeks.org/scope-rules-in-c/ https://www.geeksforgeeks.org/const-qualifier-in-c/

Casting

  • Converts variables to

different types:

– Implicit: (automatic by compiler)

  • Type promotion (upgraded to

‘data type).

– trigged by multiple data types in an expression.

  • Type “demotion” (can happen,

look out for this):

– Loss of sign, and overflow. – Example: long long float https://www.geeksforgeeks.org/type-conversion-c/

slide-5
SLIDE 5

8/21/18 5

– Explicit - “type casting”

  • (type) expression

Cautions: – Casting down:

  • Truncates

– Casting up pointers

ctutorial/global[hmv].c

Pointers

  • Stores address of a value in memory
  • Access the value by de-referencing

*aptr. – Used when reading or writing a value to a given address

  • Be aware:

– De-referencing NULL causes undefined

  • behavior. E.g., segmentation error.

ctutorial/pointers.c

slide-6
SLIDE 6

8/21/18 6

Pointers

  • Pointers to type A

references a block of sizeof(A) bytes.

  • Get the address of a

value in memory with &

  • Pointers can be

aliased, or pointed to the same address.

Carnegie Mellon

Pointers ■ Pointer to type A references a block

  • f sizeof(A) bytes

■ Get the address of a value in memory with the ‘&’ operator ■ Pointers can be aliased, or pointed to same address

ctutorial/pointers.c

  • pointers.c

– Demo of pointer arithmetic – Type affect the arithmetic

  • Adding x to a pointer A

– A + x (A+x* sizeof(TYPE_OF_PTR_A))

generate_scheduler.c

slide-7
SLIDE 7

8/21/18 7

Call by value vs. Call by reference

  • Call-by-value:

– Changes made to arguments passed to a function aren’t reflected in the calling function

  • Call-by-reference:

– Changes made to arguments passed to a function are reflected in the calling function

  • C is call by value by default, so anything past is by

value, you can use a pointer to simulate call by reference

– Parameter is an address and the address still does not change but now the content what it points to can.

passing_args.c

Arrays and Strings

  • Arrays: fixed-size collection of elements of

the same type.

– Can allocate on the stack or on the heap:

  • Strings: Null-character (‘\0’) terminated

character arrays

– Null-character tells us where the string ends – All standard C library functions on strings assume null-termination

int A[10]; //A on the stack int * A = calloc(10, sizeof(int)); //A on the heap.

slide-8
SLIDE 8

8/21/18 8

Struct

  • Collection of values under on name in a

single block of memory

– Access fields using ‘.’ – Use a pointer access via ‘’

structs.c

typedef

  • Typedefs
  • Function pointers.

typedef.c https://www.geeksforgeeks.org/function-pointer-in-c/ https://www.newty.de/fpt/fpt.html

slide-9
SLIDE 9

8/21/18 9

C program Memory Layout

  • Heap & Stack

Carnegie Mellon

C Program Memory Layout

Stack vs. Heap Data vs. Data

  • Stack:

– Local function variables, Function arguments. – Deallocated after variable leaves scope

  • Do not return pointer to a stack allocated variable
  • Do not reference the address of a variable outside its scope
  • Heap:

– Dynamically allocated (malloc/calloc)

  • Data Section:

– Global, constants.

  • Example:

// a is a pointer on the stack to a // memory block on the heap. int * a = malloc( sizeof(int) )

slide-10
SLIDE 10

8/21/18 10

Heap: Malloc, Free, Calloc

void* malloc (size_t size): allocate block of memory of size bytes does not initialize memory void* calloc (size_t num, size_t size): allocate block of memory for array of num elements each size bytes long initializes memory to zero void free(void* ptr): frees memory block, previously allocated by malloc, calloc, realloc, pointed by ptr use exactly once for each pointer you allocate size argument: should be computed using the sizeof operator sizeof: takes a type and gives you its size e.g., sizeof(int),

Memory Management Rules

  • Client should free memory allocated by client

code

  • Library should free memory allocated by

Library code

  • Number of mallocs = Number of frees

– # of mallocs > # of frees // memory leak – # of mallocs < # frees // double free.

  • Only malloc when necessary

– Persistent, variable size data structure = necessary.

mem_mgt_valgrind.sh

slide-11
SLIDE 11

8/21/18 11

Valgrind

  • Find common errors detect memory leaks
  • Common Errors

– Illegal read/write errors – Use of unitialized values – Illegal frees – Overlapping source/destination addresses

  • Questions:

– Enough memory? – Did you accidentally free? – Did something multiple times (but did not mean to) – Use something you just freed.

Valgrind

http://valgrind.org/docs/manual/quick-start.html

slide-12
SLIDE 12

8/21/18 12

Other Topics

  • Head files and Header Guards
  • Macros
  • C-Libraries.

Header Guards

  • Avoids the double inclusion problem.

#ifndef MARIA_H #define MARIA_H #endif

slide-13
SLIDE 13

8/21/18 13

Macros

  • Replace a name with a macro definition

– No function call overhead – Find and replace mechanics of a text editor.

  • Typical Uses:

– Defining constants (INT_MAX, ARRAY_SIZE) – Simple operations: MAX(a,b) – Require, Ensure

  • Caution:

– Use parenthesis around expressions, to avoid substitution problems – Do not pass expression with side effect as arguments to macros.

#define INT_MAX 0x7FFFFFFFF #define MAX(A, B) ((A) > (B) ? (A) : (B)) #define REQUIRES(COND) assert(COND) #define WORD_SIZE 4 #define NEXT_WORD(a) ((char*)(a) + WORD_SIZE)

string.h

  • Be Aware of ‘\0’ string termination.
  • dest need to be large enough to hold src
  • src contains n bytes (check).
  • src and dest do not overlap
slide-14
SLIDE 14

8/21/18 14

Common Array Methods

void memcpy( void *dest, void *src, size_t n ) void strcpy( void *dest, void *src ) char *strncat(char *dest, char *src, size_t n) char *strcat(char *dest, char *src) char *strdup( const char *s1) char *strncat (char *dest, char *src, size_t n) char *strcat (char *dest, char *src) int strncmp (char *str1, char *str2, size_t n) int strcmp(char *str1, char *str2) char *strstr (char *str1, char *str2) char *strtok (char *str, char *delimiters) size_t strlen (const char *str) void *memset (void *ptr, int val, size_t n)

stdlib.h

  • Malloc, calloc, free
  • atoi
  • System Calls

– exit(), abort()

  • Searching, Sorting

– bsearch() – qsort()

slide-15
SLIDE 15

8/21/18 15

stdio.h

  • printf, scanf
  • FILE:

– fprint,fscanf – fopen, flose

  • Redirection

Carnegie Mellon

stdio.h

Another really useful library.

Used heavily in cache/shell/proxy labs

Used for:

argument parsing

file handling

input/output ■ printf, a fan favorite, comes from this library!

getopt

  • Command line

parser.

Carnegie Mellon

Getopt

Need to include unistd.h to use

Used to parse command-line arguments.

Typically called in a loop to retrieve arguments

Switch statement used to handle

  • ptions

colon indicates required argument

  • ptarg is set to value of option

argument

Returns -1 when no more arguments present

See recitation 6 slides for more examples

int main(int argc, char **argv) { int opt, x; /* looping over arguments */ while((opt=getopt(argc,argv,"x:"))>0){ switch(opt) { case 'x': x = atoi(optarg); break; default: printf(“wrong argument\n"); break; } } }

generate_scheduler.c