Do not include return statements in the main () function in C language.

Source: Internet
Author: User

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

Related Article

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.