Lecture 2: Introduction to C Programming Language¶
Key security concept: Pointers / Arrays / Implementation for Memory management
All of the above are unsafe: If your CS61C program contains an error, it might not crash immediately but instead leave the program in an inconsistent (and often exploitable) state.
Now is 2024! We need more!
- Rust, “C-but-safe”: By the time your C is (theoretically) correct w/all necessary checks it should be no faster than Rust.
- Go, “Concurrency”: Practical concurrent programming takes advantage of modern multi-core microprocessors.
C Basics¶
./a.out and replacements
change the NAME of binary executable file:
Bash | |
---|---|
1 |
|
then you can run it by:
Bash | |
---|---|
1 |
|
Why ./
Compilation¶
C compilers map C program directly into architecture-specific machine code (string of 1s and 0s)
- Unlike Java, which converts to architecture-independent bytecode that may then be compiled by a just-in-time compiler (JIT)
- Unlike Python environments, which converts to a byte code at runtime
These differ mainly in exactly when your program is converted to low-level machine instructions (“levels of interpretation”)
Disadvantages
Advantages
Command-line arguments¶
Combined, argc and argv get the main function to accept arguments.
argc
will contain the number of strings on the command line (the executable counts as one, plus one for each argument). Hereargc
is 2:The number 2 includesBash 1
$ ./a.out myFile
./a.out
itself (really interesting)argv
is a pointer to an array containing the arguments as strings (more later re: pointers and strings).
Example
C | |
---|---|
1 2 3 4 5 6 7 |
|
Printf() formats¶
C | |
---|---|
1 2 3 |
|
Basic Types¶
sizeof(...)
intN_t
anduintN_t
Consts, Enums, #define¶
Constant, const
is assigned a typed value once in the declaration.
const
Value can't change during entire execution of program.
C | |
---|---|
1 2 3 |
|
#define
is a preprocessor directive that defines a macro. It's a CPP (C PreProcessor) Macro(宏).
- Prior to compilation, preprocess by performing string replacement in the program based on all
#define
macros. - Replace all PI with (3.14159)àIn effect, makes PI a “constant”
Enums
: a group of related integer constants.
C | |
---|---|
1 2 |
|
Typedef and struct¶
1) typedef
: create a new name for an existing type, "alias".
C | |
---|---|
1 2 |
|
2) struct
: create a new type that are structured groups of variables.
There are 3 ways to clarify a struct
, you can see here
CPP Macros¶
Appendix¶
-
linux下很多可执行文件(二进制文件)并不需要特定的后缀
-
linux系统依赖文件的权限和内容来识别和处理文件,而不是依赖文件的扩展名(chmod...)
-
Windows经常使用扩展名标识文件类型(.exe 表示可执行文件),这是windows自身“小众化”的问题,大多数系统都是不需要的