The invention relates to a method for detecting a code security hole based on constraint analysis and model checking, which can extract the source code of a C program in a constraint way and detect the security hole of the program with the model checking. The main content comprises the following steps: buffer attribute information which is involved in the source code of the C program is extracted with a constraint analysis technology; the corresponding ASSERT sentence information of attribute generation, attribute transmission and attribute constraint is inserted into variable declaration, variable assignment and function call site with the buffer attribute information; the inserted code can be taken as the input of the model checking to judge whether the program is accessible, find whether the dangerous points in the program really has an accessible path and finally find the security hole in the source code. Currently, independent model checking can not detect the security hole of the buffer and the like, the method combines the static detecting technology of the constraint analysis with the model detecting technology to realize the detection of the security hole of the buffer overflow and the like, wherein, the detecting precision of the method is higher than that of the general static detecting technology. By extracting the other dangerous function information of the source code, corresponding inserting process is carried out. The invention also can detect the security holes such as formative character string, code injection, privilege escalation, etc.