Section Error Summary (segmentation fault)

Source: Internet
Author: User
Tags printf sprintf string format

You always have a segment error when creating shared memory, and the user who has been using it in the virtual machine is your own account. The key is to create shared memory that is restricted by permissions, and then after Su Root, the program runs normally and the shared memory is created successfully. The following article is very good. This lesson to remember ~ ~

1) write data to the memory address that is protected by the system
Some memory is used by the kernel or other programs are in use, in order to ensure that the system works properly, it will be protected by the system, and can not be arbitrarily accessed.

1 #include <stdio.h>
2 Int
3 Main ()
4 {
5 int i = 0;
6 scanf ("%d", I); /* should have used &i */
7 printf ("%d\n", I);
8 return 0;
9 }

Compile and execute, at first glance, as if there is no problem oh, not just read a data and then give the output.
falcon@falcon:~/temp$ gcc-g-o segerr segerr.c– plus-G option to view debug information
falcon@falcon:~/temp$ gdb./segerr
GNU gdb 6.4-debian
Copyright 2005 Free Software Foundation, Inc.
GDB is free software, covered by the GNU general public License, and you are
Welcome to change it and/or distribute copies of it under certain.
Type "Show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "Show warranty" for details.
This GDB is configured as "I486-linux-gnu" ... Using host libthread_db Library "/Lib/tls/i686/cmov/libthread_db.so.1″.
(GDB) L – Display our source code with L (list)

01 #include <stdio.h>
02
03 Int
04 Main ()
05 {
06 int i = 0;
07
08 scanf ("%d", I); /* should have used &i */
09 printf ("%d\n", I);
10 return 0;


(GDB) b 8– set breakpoints with B (break)
Breakpoint 1 at 0x80483b7:file segerr.c, line 8.
(GDB) p I – Prints the value of the variable I with P (print) [see, the value of I here is 0 Oh]
$ = 0
(GDB) r – Run with R (run) until the breakpoint
Starting program:/home/falcon/temp/segerr
Breakpoint 1, Main () at Segerr.c:8
8 scanf ("%d", I); /* should have used &i */–[attempt to write a value to address 0]
(GDB) n – Use N (next) to perform the next step
10
Program received signal SIGSEGV, segmentation fault.
0xb7e9a1ca in _io_vfscanf () from/lib/tls/i686/cmov/libc.so.6
(GDB) C – on the top we received the SIGSEGV, and then use C (continue) to continue the execution
Continuing.
Program terminated with signal SIGSEGV, segmentation fault.
The program no longer exists.
(GDB) quit– exit GDB
Sure enough
We "accidentally" wrote &i I.
And we just started initializing I to 0, so we're not trying to store a value in memory address 0.
Added
You can view SIGSEGV information through the Man 7 signal.
falcon@falcon:~/temp$ Man 7 Signal | grep SEGV
Reformatting signal (7), please wait ...
SIGSEGV Core Invalid Memory Reference
Example 2:

01 #include <stdio.h>
02 Int
03 Main ()
04 {
05 Char *p;
06 p = NULL;
07 *p = ' x ';
08 printf ("%c", *p);
09 return 0;
10 }

It's easy to see that this example is also trying to write something to memory address 0.
Here we look at the row where the segment error is through GDB
falcon@falcon:~/temp$ gcc-g-o segerr segerr.c
falcon@falcon:~/temp$ gdb./segerr
GNU gdb 6.4-debian
Copyright 2005 Free Software Foundation, Inc.
GDB is free software, covered by the GNU general public License, and you are
Welcome to change it and/or distribute copies of it under certain.
Type "Show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "Show warranty" for details.
This GDB is configured as "I486-linux-gnu" ... Using host libthread_db Library "/lib/tls/i686/cmov/libthread_db.so.1″.
(GDB) r – Run directly, we see the throw segment error, automatically shows the occurrence of a segment error line, this is a way to find out the segment error
Starting program:/home/falcon/temp/segerr
Program received signal SIGSEGV, segmentation fault.
0x08048516 in Main () at Segerr.c:10
Ten *p = ' x ';
(GDB)
2) memory out of bounds (array out of bounds, variable type inconsistent, etc.)

1 #include <stdio.h>
2 Int
3 Main ()
4 {
5 Char test[1];
6 printf ("%c", test[1000000000]);
7 return 0;
8 }


This is a more extreme example, but sometimes it can happen, it's an obvious problem with the array going out of bounds.
Or the address is not there at all.
Example 4:

1 #include <stdio.h>
2 Int
3 Main ()
4 {
5 int B = 10;
6 printf ("%s\n", b);
7 return 0;
8 }

We're trying to output an integer as a string, what's the problem?
Because you are not familiar with debugging dynamic-link libraries,
I just found the source of printf here.
Declaration section:

01 int POS =0, cnt_printed_chars =0, I;
02 unsigned char *chptr;
03 Va_list ap;
04 /*%s Format Control Section: */
05 Case ' s ':
06 Chptr =va_arg (AP, unsigned char *);
07 i = 0;
08 while (chptr [i])
09 {...
10 Cnt_printed_chars + +;
11 Putchar (Chptr [i + +]);
12 }

Because I did not analyze the code carefully, the approximate reason might be the reason for the address out of bounds. I'm not sure, though.
If you know how to debug the printf function, please help to find out the real reason for the crossing, this paragraph error may also be
In functions such as Va_start and Va_arg. Or just take a look at this here's the printf source code analysis to see if
You can find out where the error occurred:
Http://www.wangchao.net.cn/bbsdetail_47325.html
Similarly, there are format control issues such as: sprintf
For example, try to export or store the char or int as%s, as follows:

01 #include <stdio.h>
02 #include <string.h>
03 Char c= ' C ';
04 int i=10;
05 Char buf[100];
06 printf ("%s", c); Attempting to export char type in string format
07 printf ("%s", I); Attempting to export int as String
08 memset (buf, 0, 100);
09 sprintf (buf, "%s", c); An attempt was made to convert a char type in string format
10 memset (buf, 0, 100);
11 sprintf (buf, "%s", I); Attempting to convert int type to string

3) Other
In fact, the reason is the same, is the definition of the wrong paragraph.
But more error-prone places to accumulate, not to find, or to absorb the experience accumulated by predecessors, and to avoid recurrence.
For example:
<1> Remember to initialize when the pointer is defined and remember to determine if it is null when used
<2> whether the array is initialized when it is used, whether the array subscript is out of bounds, whether the array element exists, etc.
<3> whether the variable's format control is reasonable when the variable is processed
A more good example:
I'm doing a multithreaded programming example, defining a thread array
#define Thread_max_num
pthread_t Thread[thread_max_num];
Create each thread with Pthread_create, and then use Pthread_join to wait for the thread to end
Just started
I just wait and the pthread_join can wait for each thread to end when the thread is created successfully
However, once a thread fails to be created, it is natural for a pthread_join to wait for the non-existent thread to have access to the non-existent memory, causing the segment error to occur.
Later
By constantly debugging and thinking, and get the information on the network to help, found the above causes of error and solutions
The solution is:
Initialize our thread array before creating the thread
At the end of the waiting thread, determine if the thread is our initial value
If so, it means that our thread has not been created successfully, so we cannot wait for the pull.
There are a number of common areas where errors occur, so it is easy to avoid pulling when encountering them.
But people can sometimes be negligent, and may even often have problems or other common problems.
So for some large-scale programs, how to track and find the segment error location in the program is a skill to grasp to pull.
4. How to find a segment error in a program.
There is a netizen to this to do a more comprehensive summary, in addition to thank him, I took the address to get over.
The article is called "section Error Bug debugging"
Address is: http://www.cublog.cn/u/5251/showart.php?id=173718
Should be said to be very comprehensive.
And my usual debugging methods are:
1) output (printf) information in key parts of the program, so that you can track the possible location of a segment error in your code
In order to facilitate the use of this debugging method, you can use the conditional compilation directive #ifdef Debug and #endif the printf function to include, compile the time with the-ddebug parameter can see debugging information. Conversely, do not add this parameter to debug it can.
2) debugging with GDB, where it runs to the wrong segment, it automatically stops and displays the line and line number of the error
This should be very common, if you need to debug with GDB, remember to compile the time with the-G parameter, to display debugging information
For this, the user in the "Paragraph Error bug debugging" Article creative use of such a method, so that we can execute the program when it is possible to dynamically capture the location of the error may occur:
The system invokes GDB to output debug information by SIGSEGV the signal.
If we add the above-mentioned conditional compilation, then we can make the debugging of the section error very convenient.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.