Session 3: Dynamic Memory Allocation. Strings.
Tasks
There is a directory for each task number. Makefiles are provided for all of them.
allocation types and alignement
This is a simple application that allocates some memory and prints the obtained addresses.
Observe how all the addresses are 8 bytes aligned (or 16 bytes on a 64bits system).
If you eliminate the 8 byte alignment, the pointers are also 4K aligned
Why is the first address so different from the rest ?
massif
Analyze the source code. There are several functions allocating memory on the heap.
Build the application
Run valgrind with the “massif” tool to profile the heap usage of the application.
valgrind --tool=massif --time-unit=B ./massif
The time unit option can be “i” (instruction), “ms” (millisecond), “B” (byte). This application runs for a small amount of time, so “B” is the best in this case.
A massif.out.$PID file will be created
Display the profiling data:
Free the memory at the end of the f() and g() functions and redo the profiling
Compare the 2 snapshots.
information leak
Freeing memory does not destroy the data. This small application demonstrates that.
Analyze the source and build the application.
Use pahole
to display the memory layout of “struct data”. Information can be leaked in those holes.
compilers might align the fields in a structure
pahole uses debugging information from the binary to display the layouts of data structures
-
Install the dwarves
package if pahole is not found
Implement 2 solutions that will prevent information leak
corruption
Analyze the source code.
Build and run.
Supply an invalid index (negative). What happens ? Try with an index of -1. What now ? Why ?
Run under gdb with the same index. Find out what is stored at that memory location.
gdb corrupt
breakpoint 27
run -1 70
GDB commands for displaying memory contents:
x/bx address
x/wx ptr - 1
You should see something like:
string length
The application in over.c reads a user name and a password from standard input.
It displays a welcome message if the combination is right.
What happens when you supply the correct information ?
Fix the application so that the string format won't overrun the allocated buffer.
tokenize
This application splits a string containing the PATH environment variable and displays each path.
Eventually, it tries to run “gcc”, but fails.
Find out what is wrong and fix it
Hint: strtok
Hint: use strdup