Fichas
Head First C
Fichas del conjunto (53)
- 1Connecting input and outputThe | symbol is a
pipe that connects
the Standard Output
of one process to the
Standard Input of
another process. - 2Stdin , stdout, stderrThe printf() function sends data to the Standard Output.The Standard Output goes to the display
by default.You can redirect the Standard Output to a file by using > on the command line. scanf() reads data from the Standard Input.The Standard Input reads data from the keyboard by default. You can redirect the Standard Input to read a file by using < on the command line.The Standard Error is reserved for outputting error messages. You can redirect the Standard Error using 2>. - 3Scanf()scanf(“%i”, &x) will allow a user to enter a number x directly.
fgets(buf, size, stdin) is a simpler way to enter text. - 4The codeA lot of operating
systems place the code right down in the
lowest memory addresses. The code segment
is also read-only. This is the part of the
memory where the actual assembled code
gets loaded. - 5The constantsConstants are also created when the program
first runs, but they are stored in read-only
memory. Constants are things like string
literals that you will need when the program
is running, but you’ll never want them to
change. - 6The globalsA global variable is a variable that lives
outside all of the functions and is visible to
all of them. Globals get created when the
program first runs, and you can update them
freely. - 7The heapThe heap is for dynamic
memory: pieces of data that get created
when the program is running and then hang
around a long time. - 8The stackStack
This is the section of memory used for local
variable storage. Every time you call a
function, all of the function’s local variables
get created on the stack. It’s called the stack
because it’s like a stack of plates: variables get
added to the stack when you enter a function,
and get taken off the stack when you leave.
Weird thing is, the stack actually works upside
down. It starts at the top of memory and
grows downward. - 9Array decayBecause array variables are slightly
different from pointer variables, you need
to be careful when you assign arrays
to pointers. If you assign an array to a
pointer variable, then the pointer variable
will only contain the address of the array.
The pointer doesn’t know anything about
the size of the array, so a little information
has been lost. That loss of information is
called decay.
Every time you pass an array to a
function, you’ll decay to a pointer, so
it’s unavoidable. But you need to keep
track of where arrays decay in your code
because it can cause very subtle bugs. - 10sizeof(stuff)The sizeof operator returns the
space taken by a piece of data.
sizeof(a pointer) returns
4 on 32-bit operating systems and 8
on 64-bit. - 11& and *The & operator finds the address of
a variable.The * operator can read the contents
of a memory address. The * operator can also set the
contents of a memory address. - 12Variables and memoryEvery time you declare a variable, the computer creates
space for it somewhere in memory. If you declare a
variable inside a function like main(), the computer
will store it in a section of memory called the stack. If
a variable is declared outside any function, it will be stored
in the globals section of memory. - 13Breaks and continuebreaks don’t break out
of ifs
continue check the condition again - 14&& and || vs & and |The & and | operators will always
evaluate both conditions, but && and ||
can often skip the second condition. - 15stringsC is more low-level than most other languages, so instead
of strings, it normally uses something similar: an array of
single characters. An array is just a list of
things given a single name. - 16Checking the exit statuson windows → echo %ErrorLevel%
on mac / linux → echo $? - 17The printf()The printf() function is used to display formatted output. It
replaces format characters with the values of variables, like this:
The first parameter will be inserted here as a string.
printf("%s says the count is %i", "Ben", 21);
You can include as many parameters as you like when you call the printf()
function, but make sure you have a matching % format character for each one. - 18The 3 C standardsThere are three C standards that you may
stumble across. ANSI C is from the late 1980s
and is used for the oldest code. A lot of things
were fixed up in the C99 standard from 1999. And
some cool new language features were added in
the current standard, C11, released in 2011. The
differences between the different versions aren’t
huge, and we’ll point them out along the way. - 19PreprocessingThe first thing the compiler needs to do is fix the source. It needs to add in
any extra header files it’s been told about using the #include directive.
It might also need to expand or skip over some sections of the program.
Once it’s done, the source code will be ready for the actual compilation. - 20CompilationThe C programming language probably seems pretty low level, but
the truth is it’s not low level enough for the computer to understand. The
computer only really understands very low-level machine code
instructions, and the first step to generate machine code is to convert
the C source code into assembly language symbols - 21AssemblyThe compiler will need to assemble the symbol codes into machine or
object code. This is the actual binary code that will be executed by
the circuits inside the CPU - 22LinkingOnce you have all of the separate pieces of object code, you need to
fit them together like jigsaw pieces to form the executable program.
The compiler will connect the code in one piece of object code that
calls a function in another piece of object code. Linking will also make
sure that the program is able to call library code properly. Finally, the
program will be written out into the executable program file using
a format that is supported by the operating system. The file format
is important, because it will allow the operating system to load the
program into memory and make it run. - 23The make tool's bullet pointsThe dependencies.
Which files the target is going to be generated from.
The recipe.
The set of instructions it needs to run to generate the file. - 24Structuresuse them to pass less parameters to functions and have a cleaner code
use typedef struct name
{
} allias - 25(*t).age or *t.agethe first is the age at the t struct pointer (aka t -> age)
the second is the addres of t.age - 26unionstypedef union
unions let you reuse memory space
A union is different. A union will use the space for just one
of the fields in its definition. So, if you have a union called
quantity, with fields called count, weight, and volume,
the computer will give the union enough space for its largest
field, and then leave it up to you which value you will store in
there. Whether you set the count, weight, or volume field,
the data will go into the same space in memory - 27the union's downfallThe compiler won’t be able to keep track of the fields that are set
and read in a union, so there’s nothing to stop us setting one field
and reading another. - 28enumenum colors {RED, GREEN, PUCE};
If you want to record a day of the week, you only
want to store MONDAY, TUESDAY, WEDNESDAY, etc. You
don’t need to store the text, because there are only ever going
to be seven different values to choose from.
That’s why enums were invented.
enum lets you create a list of symbols - 29bitfieldsA bitfield lets you specify how many bits an individual
field will store. For example, you could write your
struct like this:
unsigned int ismine :1;
Bitfields allow you to store a field with
a custom number of bits.
Bitfields should be declared as
unsigned int. - 30linked listsA linked list is an example of an abstract data structure.
It’s called an abstract data structure because a linked list is
general: it can be used to store a lot of different kinds of data. - 31valgrindvalgrind --leak-check=full ./spies
valgrind checks for memory
leaks.
valgrind works by intercepting
the calls to malloc() and
free().
When a program stops running,
valgrind prints details of what’s
left on the heap.
If you run your program several times,
you can narrow the search for the
leak.
valgrind can tell you which lines
of code in your source put the data
on the heap.
valgrind can be used to check
that you’ve fixed a leak.
If you compile your code with debug
information, valgrind can give
you more information. - 32qsort()The C Standard Library has a sorting function called
qsort().
qsort() accepts a pointer to a comparator function
that can test for (in)equality.
The comparator function will be passed pointers to two
items in the array being sorted.
If you have an array of data, you can associate functions
with each data item using function pointer arrays. - 33function pointersFunction pointers store the addresses of functions.
The name of each function is actually a function pointer.
If you have a function shoot(), then shoot and
&shoot are both pointers to that function.
You declare a new function pointer with
return-type(*var-name)(param-types).
If fp is a function pointer, you can call it with
fp(params, ...).
Or, you can use (*fp)(params,...). C will work
the same way. - 34variadic functionsA function that takes a variable number of parameters is
called a variadic function. The C Standard Library
contains a set of macros that can help you create your
own variadic functions. - 35creating variadic functions1 Include the stdarg.h header.
All the code to handle variadic functions is in stdarg.h, so you
need to make sure you include it.
2 Tell your function there’s more to come...
Remember those books where the heroine drags the guy
through the bedroom and then the chapter ends “...”? Well,
that “...” is called an ellipsis, and it tells you that something
else is going to follow. In C, an ellipsis after the argument of a
function means there are more arguments to come.
3 Create a va_list.
A va_list will be used to store the extra arguments that
are passed to your function.
4 Say where the variable arguments start.
C needs to be told the name of the last fixed argument. In the
case of our function, that’ll be the args parameter.
5 Then read off the variable arguments, one at a time.
Now your arguments are all stored in the va_list, you can read
them with va_arg. va_arg takes two values: the va_list and
the type of the next argument. In your case, all of the arguments
are ints.
6 Finally...end the list.
After you’ve finished reading all of the arguments, you need to tell
C that you’re finis - 36variadic functions bullet points Functions that accept a variable
number of arguments are called
variadic functions.
You will need at least one fixed
parameter.
To create variadic functions, you need to include the stdarg.h header file.
Be careful that you don’t try to read
more parameters than you’ve been
given.
The variable arguments will be stored
in a va_list.
You will always need to know the data type of every parameter you read.
You can control the va_list using
va_start(), va_arg(), and va_end(). - 37"" vs <>If you use angle brackets in an #include statement, the compiler
won’t look for the headers in the current directory; instead, it will search
for them in the standard header directories which usually are:
/usr/local/include
/usr/include - 38creating archivesar -rcs libhfsecurity.a encrypt.o checksum.o
The r means the .a
file will be updated
if it already exists.
The c means that the archive
will be created without any
feedback.
The s tells ar to create
an index at the start of
the .a file. - 39using static archivesgcc test_code.c -lhfsecurity -o test_code
Remember to list your source
files before your -l libraries.
hfsecurity tells the compiler to look
for an archive called libhfsecurity.a.
If you’re using several archives,
you can set several -l options.
Do you need a - I option?
It depends on where you
put your headers. - 40What's the kernel?What’s the kernel?
On most machines, system calls are functions that live inside the kernel of the operating system. But
what is the kernel? You never actually see the kernel on the screen, but it’s always there, controlling your
computer. The kernel is the most important program on your computer, and it’s in charge of three things:
proceses, memory and hardware
System calls are the functions that your program uses to talk to the kernel. - 41ProcessesProcesses
No program can run on the system without the kernel loading it into memory. The kernel creates
processes and makes sure they get the resources they need. The kernel also watches for processes that
become too greedy or crash. - 42MemoryMemory
Your machine has a limited supply of memory, so the kernel has to carefully ration the amount of memory
each process can take. The kernel can increase the virtual memory size by quietly loading and unloading
sections of memory to disk. - 43HardwareHardware
The kernel uses device drivers to talk to the equipment that’s plugged into the computer. Your program
can use the keyboard and the screen and the graphics processor without knowing too much about them,
because the kernel talks to them on your behalf. - 44system()The system() function is an easy way of running other
programs from your code—particularly if you’re creating
a quick prototype and you’d sooner call external programs
rather than write lots and lots of C code. - 45exec()The exec() functions replace the current process by
running some other program. You can say which command-
line arguments or environment variables to use, and when the
new program starts it will have exactly the same PID as the
old one. - 46execl() , execlp(), execle() usageThe program.
This might be the full pathname of the program—execl()/
execle()—or just a command name to search for—execlp()—
but the first parameter tells the exec() function what program it
will run.
The command-line arguments.
You need to list one by one the command-line arguments you want
to use. Remember: the first command-line argument is always the
name of the program. That means the first two parameters passed
to a list version of exec() should always be the same string.
NULL.
That’s right. After the last command-line argument, you need a
NULL. This tells the function that there are no more arguments.
Environment variables (maybe).
If you call an exec() function whose name ends with ...e(), you can
also pass an array of environment variables. This is just an array of strings
like "POWER=4", "SPEED=17", "PORT=OPEN" - 47execv(), execvp(), execve()are the same as execl(), execle() and execlp() except they take vectors as arguments like this :
execv("/home/flynn/clu", my_args);
execvp("clu", my_args);
The only difference between these two functions is that
execvp will search for the program using the PATH variable. - 48figureing out which exec to useYou can figure out which exec() function you need by
constructing the name. Each exec() function can be followed
by one or two characters that must be l, v, p, or e. The
characters tell you which feature you want to use. So, for the
execle() function:
execle = exec + l + e = LIST of arguments + an ENVIRONMENT
The l and v characters always come before p and e,
and the p and e characters are optional.
execl() = list of args.
execle() = list of args + environment.
execlp() = list of args + search on path.
execv() = array of args.
execve() = array of args + environment.
execvp() = array of args + search on path - 49fork()fork() makes a complete copy of the current
process. The brand-new copy will be running
the same program, on the same line number. It
will have exactly the same variables that contain
exactly the same values. The only difference is
that the copy process will have a different process
identifier from the original.
The original process is called the parent
process, and the newly created copy is called
the child process. - 50using fork()You call fork() like this:
pid_t pid = fork();
fork() will actually return an integer value that is 0 for
the child process and positive for the parent process.
The parent process will receive the process identifier of
the child process.
But what is pid_t? Different operating systems use
different kinds of integers to store process IDs: some
might use shorts and some might use ints. So pid_t
is always set to the type that the operating system uses. - 51fileno()fileno() tells you the descriptor
fileno() is one of the few system functions that doesn’t return
–1 if it fails. As long as you pass fileno() the pointer to an
open file, it should always return the descriptor number. - 52dup2()dup2() duplicates data streams
- 53—
Información
- Descripción
- Computer Science Fichas sobre Head First C, creado por Mircea Chira el 28/11/2016.
- Creado por
- Mircea Chira
- Visitas
- 1
- Valoración