06. Memory
Command line
- input-output redirection:
program > file: redirect output
program < file: redirect input
program1 | program 2: redirect output of program1 to input of program2
E. g. (try i):
Calendar: cal
Calendar to file: cal > file
Words counter: wc < file (also lines and characters counter)
What this does: cal | wc
Print some: echo some words with spaces
- note spaces are gone. Why?
- Print exact string"
[@sugon ~]$ echo 'dafg sdfg sdfg sdfgdfger qgrdqwfgwerg erg ergfer xcv werg wergwe wer'
Task: print some strings and count words/characters/lines
less:
- used to browse text page by page
e. g. less /usr/share/dict/words
q to quit
maan:
- browse documentation to any system component (if any)
uses less for browsing
e. g. man man or man cal
seq:
- generate and display number sequences
seq 10
seq 5 -1 0
man seq
Static Memory allocation
What this code does?
Compile it statically:
with compile
or with cc -static
Try it:
on 3 2 1 0
on 7 6 5 4 3 2 1 0
- Describe what you see (Hint: use previous class)
on 100 99 98 … 0 (user seq and | redirection)
Notice «segmentation fault»: trying to access (virtual) memory address, that is not mapped in TLB to any physical address
Dynamic memory allocation
malloc(nbytes): allocate nbytes of memory
- try to detect maximum possible size of malloc-ed memory
- notice the address changes randomly (?)
IRL you need to free() all the memory you've malloc-ed:
Note: it's safe to print p after it was freed
It is unsafe to free that already free-d (try it)
It is highly unsafe to read/write into already free-d memory, because of possible memory corruption without actual address violation (try it for various values of n)
Important: while memory/stack corruption is deadly for a process, it is completely safe for other processes, because of memory isolation
H/W
- write a program that detects maximum possible size of malloc-ed memory
read man malloc to learn how malloc() reports a failure
spoiler:
do not forget to free()