How to keep bugs away from you?

        If you want bugs to stay away from you, of course you must rely on the blessing of Buddha~ 

/*
 * **************************************************************************
 * ********************                                  ********************
 * ********************      COPYRIGHT INFORMATION       ********************
 * ********************                                  ********************
 * **************************************************************************
 *                                                                          *
 *                                   _oo8oo_                                *
 *                                  o8888888o                               *
 *                                  88" . "88                               *
 *                                  (| -_- |)                               *
 *                                  0\  =  /0                               *
 *                                ___/'==='\___                             *
 *                              .' \\|     |// '.                           *
 *                             / \\|||  :  |||// \                          *
 *                            / _||||| -:- |||||_ \                         *
 *                           |   | \\\  -  /// |   |                        *
 *                           | \_|  ''\---/''  |_/ |                        *
 *                           \  .-\__  '-'  __/-.  /                        *
 *                         ___'. .'  /--.--\  '. .'___                      *
 *                      ."" '<  '.___\_<|>_/___.'  >' "".                   *
 *                     | | :  `- \`.:`\ _ /`:.`/ -`  : | |                  *
 *                     \  \ `-.   \_ __\ /__ _/   .-` /  /                  *
 *                 =====`-.____`.___ \_____/ ___.`____.-`=====              *
 *                                   `=---=`                                *
 * **************************************************************************
 * ********************                                  ********************
 * ********************      				             ********************
 * ********************         佛祖保佑 永远无BUG        ********************
 * ********************                                  ********************
 * **************************************************************************
 */

End of article~


Ahem, let’s start the text directly~


The structure of this article:

        O, Foreword

        1. What is a bug?

        Second, what is Debug?

        3. Debug of general compiler

                (1) Print output

                (2) Single-step debugging

                (3) Set breakpoints

                (4) Monitoring and memory observation

                (5) Set assertion

        Fourth, compilation habits are very important

                (0) Write code from the perspective of memory

                (1) High cohesion and low coupling of functions

                (2) Write comments

                (3) Leave appropriate blank space

        Five, I want to tell you

 O, Preface

        1. Contents of the Error Experience Sharing Column in the Connection Column of this article (The opening article is attached at the end of the article)

        2. We know that common errors during coding include compilation errors, linking errors, runtime errors, etc. The focus of this article isRuntime errors-specifically-The code you write cannot achieve what you want. The desired effect, but you don't know where the mistake is.

        3. Debug is the action we take after we know there is an error. In order to make the program achieve the predicted running target, we have to find the bugs we wrote, but this usually takes a long time. If we can reduce the occurrence of bugs from the source, write fewer bugs, or not set up so many obstacles for ourselves to debug in the future, then this will virtually save us time and improve efficiency.

        

 1. What is a bug?

        The original meaning of bug is "insect" or "bug". Now it generally refers to some undiscovered defects or problems hidden in computer systems or programs.
Program loopholes.

        Grace Murray Hopper, the founder of "Bug", on September 9, 1947, after Grace Hopper programmed 17,000 relays on the Harvard Mark II, technicians were running the whole machine , the computer suddenly stopped working. So they climbed up to find out the reason, and found that there was a moth between the contacts of a set of relays inside the huge computer. This was obviously caused by dry moths being attracted by light and heat and flying to the contacts. clicked on, and was killed by high voltage.

        So in the report, Heber attached the moth with tape and used "bug" to mean "an error in the computer program."         So, the term "Bug" is still used today.

2. What is Debug?

         De- means to reduce or eliminate; the process of debugging is called Debug (eliminate bug).

         You can roughly locate the problem by isolating and shielding the code, determine the cause of the error, then repair the code and retest.

         Debug is also a version, opposite to it is the Release version. The two versions have different differences:

 the difference:

Debug takes up a large amount of memory, contains debugging information, and is not optimized compared to the Release version;

The Release version does not contain debugging information and takes up less memory due to relevant optimizations;

3. Debug of general compiler

1.Print output

       Use the printf function to follow the program and output the value of the variable.

 e.g.1

Write a program that can produce output that meets the requirements based on input.

The program must contain a function that can find the longest word in a string and output it.

enter

A line can contain a string of English uppercase and lowercase letters and spaces .

output

By calling a function, output the longest word in this string.

Sample

standard input
Einstein had been a famous physicist after then but he still wore the same old overcoat
standard output
physicist

 To understand the question, let’s look directly at the code:

#include<stdio.h>
int main()
{
	char arr[50][50] = { 0 };
	int brr[50] = { 0 };
	int j = 0, p;
	char ch;
	
	for (;;)
	{
		p = 0;
		for (; (ch = getchar()) != '\n';)
		{
			
			if (ch != ' ')//如果不是‘ ’则继续读取
			{
				arr[j][p] = ch;
				p++;
			}
			if ((ch) == ' ')//如果是‘ ’则换到j的下一行
			{
				arr[j][p] = 0;
				brr[j] = p;//(计数)
				j++;
				p = 0;
			}
		}
		if ((ch) == '\n')
		{ 
			brr[j] = p;
			break; 
		}
	}
	int tem = 0, k = 0;
	for (; k < 50; k++)//找到最长字符串的长度
	{
		if (tem < brr[k])
		{
			tem = brr[k];
		}
	}
	
	int m = 0;
	for (; m < 50; m++)
	{
		printf("%d\n",m);//时时输出m,查看第几个字符串是最长字符串
		if (brr[m] == tem)
		{
			break;
		}
	}//找到最长字符串对应的行数j
	
	
	printf("%s\n", arr[m]);
	
	return 0;
}

        In the last for loop, m is used to record which string it is, and printf is used to continuously output m. When m is 5, m == tem is the number of lines of the longest string found previously.

         So, this code is a solution to the problem.

2. Single-step debugging

        When some programs are running, we will see error messages, but we don’t know exactly where the error occurred. At this time, we can locate the error through single-step debugging The position.

For example, when we run this code, we find that the program hangs, but we don’t know which line has the problem.

e.g.2——When we run it, we find that the program has an infinite loop, but because in actual situations, code projects are often very complex, we generally cannot directly visually detect the errors.

#include<stdio.h>
int main()
{
	printf("haha\n");
	main();
	
	return 0;
}

e.g.3 - When the program is running, we learn that the program has an array out of bounds, but we do not know which line of code caused the array out of bounds (because we must find the code before we can modify and improve the code)


int main()
{

	char arr[10];
	scanf("%s", arr);
	return 0;
}

At this time it is time for single-step debugging to come into play to solve the problem:

e.g.2 Solution

When the program runs to main(), press f10 again

 The program crashes

 ——Conclusion: There is a problem in line 6

e.g.3 Solution

 When the program reaches scanf() and you press f10 again, the program reports an error

 ——Conclusion: The scanf() function reads too much data, causing the array to go out of bounds

 3. Set breakpoints

        In VS2019, when we click the label of the code line on the left with the mouse, a red origin will appear, which is the breakpoint

 Set breakpoint:

        ​ ​ ​Click the vertical line on the left side of the code line with the mouse, and a breakpoint will appear; (click again to cancel the breakpoint)

        Set the input cursor on the line where you want to break the point, and press f9, a breakpoint will also appear. (Press f9 again to cancel settings)

Use breakpoints:

        Breakpoints are used in conjunction with f5. Each time f5 is pressed, the program will jump to the next logical breakpoint.

 4. Monitoring and memory observation

When we are debugging, we want to more intuitively observe the changing process of the value of the variable. At this time we can turn on monitoring

Press f10 to enter the debugging state. Note that in the debugging state, we find the monitoring window in the window as shown in the figure:

 (All four monitoring windows are available. If you use it for the first time, you can choose any one)

 In the monitoring window, we can monitor the changing process of variables at any time:

Memory window:

Click the image to find the memory window

 Through the memory window, we can see the creation and destruction of variables within the function in memory (attached at the end of the article)

Since I have shared it before, I won’t go into details here.​ 

5. Set up assertions

assert() function, used to catch program errors during debugging

e.g.4——Simulating the strcpy() function

We do not want the incoming p1 and p2 to be null pointers. Dereferencing null pointers is very dangerous! So we use assertion assert here, the two pointers are not null pointers


#include<stdio.h>
#include<assert.h>
void my_strcpy(char* p1,const char* p2)
{
	assert(p1 != NULL);
	assert(p2 != NULL);
	while(*p1++ = *p2++)
	{
		;
	}
}
int main()
{
	char str1[20] = "xxxxxxxxxxxxxx";
	char str2[] = "hello";

	my_strcpy(str1,str2);

	printf("%s\n", str1);
	printf("%s\n", str2);
	return 0;
}

  (This code is very clever, it vividly reflects the compactness of C language.)

If so, then the program will report the precise error message:

assert()

        The header file where it is located: <assert.h>

        Function prototype: void assert (int expression);

        Parameter: expression is the expression to be detected

        Return value: No return value

        The usage of assert() is very simple. We just need to pass in an expression, and it will calculate the result of the expression: if the result of the expression is "false", assert() will print out the assertion failure information and call abort( ) function terminates the execution of the program; if the expression evaluates to "true", assert() does nothing and the program continues execution.

        If you want to disable this assertion function, just
 
        #define NDEBUG

        It is defined at the beginning of the code, before including <assert.h>.

Fourth, compilation habits are very important

 (0)Write code from the perspective of memory

When we write code, we need to be memory aware. Look at the code as memory and the array as a continuous linear list. If it is a local variable, it is created in the stack area, with the address first high and then low, etc.

(1) High cohesion and low coupling of functions

When we write projects, we often need to implement multiple functions. If we write all the codes together, on the one hand, the logic will be unclear, which will be inconvenient during debugging and set up obstacles for ourselves. On the other hand, if we If you want to use a function of a function again, you have to rewrite it again.

If we encapsulate the project into functions with different functions and call them when using them, the logic of the code will be greatly improved, and the amount of code can be reduced and efficiency improved.

(2) Write notes

  1. Explain the code: Comments can be used to explain the meaning and function of the code, helping other developers understand your code.

  2. Improve code readability: Comments can make code more readable and readable. Comments can make the code easier to understand, especially in some complex algorithm or logic code.

  3. Convenient debugging: Comments can be used to record the execution flow of the program, which can help error diagnosis and debugging.

  4. Convenient maintenance: Comments can record the change history and maintenance records of the code, making it easier to maintain and modify the code in the future.

  5. Improve code quality: Comments can force writers to think about the logic of the code, which helps improve code quality.

(3) Leave appropriate blank space

        Appropriate white space can improve the readability of the code and make it easier to understand.

Five, I want to tell you

        The best debugging is to reduce the number of bugs written. Before writing a program, you should estimate the feasibility and logic of the code based on the knowledge of memory and data structure, and mentally construct the implementation method of your own ideas.

        Dare to discover and admit your mistakes

        Debugging is an iterative process that requires constant trying and testing until all errors are found and resolved.

come on! 


Compilation error resolutionicon-default.png?t=N7T8https://blog.csdn.net/2301_79465388/article/details/133919788?spm=1001.2014.3001.5502 Creation and destruction of function stack framesicon-default.png?t=N7T8https://blog.csdn.net/2301_79465388/article/details/134256464?spm=1001.2014.3001.5502

 Article review


Table of contents

 O, Preface

 1. What is a bug?

2. What is Debug?

3. Debug of general compiler

1.Print output

2. Single-step debugging

 3. Set breakpoints

 4. Monitoring and memory observation

5. Set up assertions

Fourth, compilation habits are very important

                (0)Writing code from the perspective of memory

(1) High cohesion and low coupling of functions

(2) Write notes

(3) Leave appropriate blank space

Five, I want to tell you


Finished~

Reprinting without the author's consent is prohibited

Guess you like

Origin blog.csdn.net/2301_79465388/article/details/134256437