深入探索GDB调试技巧与C/C++代码调试
1. 随机数与缓冲区溢出模拟
在调试过程中,有时需要模拟一些复杂情况,比如缓冲区溢出。以下是一段模拟缓冲区溢出的代码:
// Seed the random number generator so that each run is different. srand(time(NULL)); // Loop count - a nice high number. int n = 800000; // We want the chance of overrun to be 1 in N just to make this hard // to catch. int thresh = RAND_MAX / n; for (i = 0; i < n; i++) { // Overrun if the random number is less than the threshold int len = (rand() < thresh) ? buflen + 1 : buflen; ovrrun(buf, text, len); } // Overrun is easy to detect but hard to catch. int overran = (strlen(buf) > buflen); if (overran) printf("OVERRUN!\n"); else printf("No overrun\n"); free(buf); return overran;这段代码的流程如下: