Let's look at two pieces of code first--
Error code:
#include "string.h" #include <stdlib.h> #include <stdio.h>void test (char * * dest, char * src, int n) {(*dest) = (char*) malloc (sizeof (char) * n); strcpy (*dest, SRC);} int main (int argc, char** args) {char * * p = Null;char str[] = "Test segmentation fault"; int len = sizeof (str); Test (P, str , Len);}
Correct code:
#include "string.h" #include <stdlib.h> #include <stdio.h>void test (char * * dest, char * src, int n) {(*dest) = (char*) malloc (sizeof (char) * n); strcpy (*dest, SRC);} int main (int argc, char** args) {char * p = null;char str[] = "Test segmentation fault"; int len = sizeof (str); Test (&p, STR, len);}
If you useCoredump+gdbdebugging, you will find that the error program appears commonSegmentation FaulT error.
cause : This error is often caused by a program accessing an address space that has no access or is not mapped by the MMU.
Analysis: When an application starts, the system establishes a process for it, which has a separate virtual memory space (vma:vertual), such as:
For example, an segmentation fault error occurs when an application process accesses an area of a red line callout.
Debug: Next, use Eclipse's C + + version (or Eclipse install CDT) to debug the above error example, as shown below:
We see an error cannot access memory at address 0x0when we use Eclipse to try to access the value of a pointer *p with the address of 0x0. (Verified by our above analysis, 0x0 address no access)
Fault Analysis: now analyze and analyze the error of the program where it went wrong.
1)char * * p = NULL; This sentence executes after the pointer pointer P's value is 0x0, that is, the address of the *p pointer is 0x0.
2)(*dest) = (char*) malloc (sizeof (char) * n); This sentence analysis: first the equation to the right (char*) malloc (sizeof (char) * N) execution is not wrong, get an assigned address value, then assign the address value to the left *dest when the problem arises, through the preceding analysis know * The address of the Dest pointer is the address of the *p pointer above is 0x0, this address through the previous analysis is not authorized to access , application assignment is access, this is the source of the problem.
right: now to compare the right, such as:
You can see that the address value of *dest is &p is 0x28ff08, this address is accessible , so when we assign the assigned address value to *dest is completely no problem.
ECLIPSE+CDT Debug Segmentation fault Error