OSTEP第14章测试题

1. First, write a simple program called null.c that creates a pointer to an integer, sets it to NULL, and then tries to dereference it. Compile this into an executable called null. What happens when you run this program?
#include<iostream>
using namespace std;
int main(){
    int *p=NULL;
    cout<<*p<<endl;
}

2. Next, compile this programwith symbol information included (with the -g flag). 
Doing so let’s put more information into the executable, enabling the debugger to access more useful information about variable names and the like. 
Run the program under the debugger by typing gdb null and then, once gdb is running, typing run. What does gdb show you?

3. Finally, use the valgrind tool on this program. 
We’ll use the memcheck tool that is a part of valgrind to analyze what happens.
 Run this by typing in the following: valgrind --leak-check=yes null. What happens when you run this? Can you interpret the output from the tool?
siuwhat@siuwhat-PC:~/Desktop$ valgrind --tool=memcheck --leak-check=yes ./null
==4271== Memcheck, a memory error detector
==4271== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4271== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4271== Command: ./null
==4271== 
==4271== Invalid read of size 4
==4271==    at 0x1088BE: main (null.cpp:5)
==4271==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==4271== 
==4271== 
==4271== Process terminating with default action of signal 11 (SIGSEGV)
==4271==  Access not within mapped region at address 0x0
==4271==    at 0x1088BE: main (null.cpp:5)
==4271==  If you believe this happened as a result of a stack
==4271==  overflow in your program's main thread (unlikely but
==4271==  possible), you can try to increase the size of the
==4271==  main thread stack using the --main-stacksize= flag.
==4271==  The main thread stack size used in this run was 8388608.
==4271== 
==4271== HEAP SUMMARY:
==4271==     in use at exit: 0 bytes in 0 blocks
==4271==   total heap usage: 1 allocs, 1 frees, 72,704 bytes allocated
==4271== 
==4271== All heap blocks were freed -- no leaks are possible
==4271== 
==4271== For counts of detected and suppressed errors, rerun with: -v
==4271== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
段错误
4. Write a simple program that allocates memory using malloc() but forgets to free it before exiting. 
What happens when this program runs?
 Can you use gdb to find any problems with it? 
How about valgrind (again with the --leak-check=yes flag)?

2020-07-09 17:57:55

原文地址:https://www.cnblogs.com/otakus/p/13275157.html