Let's take a look at this program:
[Cpp]
# Include <stdio. h>
Typedef unsigned char bool;
Typedef struct _ person;
Struct _ person {
Bool sex;
};
Person main (){
Person xingwang;
Xingwang. sex = 0;
Return xingwang;
}
Do you think an error will be reported for such a simple and clear program? If you are the same as me, you will certainly not report an error. Please continue to read the compiled assembly code of this program:
[Plain]
. File "struct. c"
. Text
. Globl main
. Type main, @ function
Main:
Pushl % ebp
Movl % esp, % ebp
Subl $16, % esp
Movl 8 (% ebp), % eax
Movb $0,-1 (% ebp)
Movzbl-1 (% ebp), % edx
Movb % dl, (% eax)
Leave
Ret $4
. Size main,.-main
. Ident "GCC: (GNU) 4.4.6 20110731 (Red Hat 4.4.6-3 )"
. Section. note. GNU-stack, "", @ progbits
Pushl % ebp stores the current base address, which is used when the function exits
Movl % esp, % ebp base address of the current function
Subl $16, % esp in the stack, allocate 16 bytes to store local variables
Movl 8 (% ebp), where % eax calls the main () function, the return value is stored here. (Obviously, there is no function to call main (). This address is uncertain)
Movb $0,-1 (% ebp) is assigned a value for xingwang. sex
Movzbl-1 (% ebp), $ edx
Movb % dl, (% eax) Assign xingwang to the memory address pointed to by eax
The problem lies in movl 8 (% ebp) and % eax. After debugging with GDB, it is found that the value of % ebp + 8 is 0x1, that is, the return value of the function is stored in the memory unit 0x1. Obviously, this memory unit cannot be operated by users.
Therefore, a Segment error or Segment Fault will be prompted during the final running of the C program.
Author: topasstem8