The C program compiled by GCC has a segment error.

Source: Internet
Author: User

The program is compiled and runs properly in VC 6.0,
A "segment error" occurs during compilation under GCC ",
Finally, it is found that the cycle is caused by the definition of Large variables,
I defined some variables in a while loop, for example:
While ()
{
Char A [50];
Char B [50];
Char C [20];
Memset (A, 0, 50 * sizeof (char ));
Memset (B, 0, 50 * sizeof (char ));
Memset (C, 0, 20 * sizeof (char ));
......
}

A segment error occurs during GCC compilation and running,
Generally, a segment error means that the accessed memory exceeds the memory space of the program provided by the system,
This value is usually stored by GDTR, which is a 48-bit register,
The 32-bit table stores the gdt table pointed to by it, and the last 13 BITs are saved to the corresponding gdt subscript,
The last three digits include whether the program is in the memory and the running level of the program in the CPU,
Gdt is a table in 64-bit units,
In this table, the code segment for running the program and the start address of the data segment are saved, and the corresponding
Segment limit, page exchange, program running level, memory granularity, and so on.
Once a program is accessed out of bounds, the CPU will generate corresponding exception protection,
Then segmentation fault appears.

The solution is to put variable definitions out of the loop. In fact, these most basic programming
Knowledge we have talked about as early as the code optimization of compilation principles. If you don't pay attention to it, problems may occur sometimes.

The code is changed to the following format, so there is no error in compiling and running.

Char A [50];
Char B [50];
Char C [20];
While ()
{
Memset (A, 0, 50 * sizeof (char ));
Memset (B, 0, 50 * sizeof (char ));
Memset (C, 0, 20 * sizeof (char ));
......
}

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.