非常教程

C参考手册

错误处理 | Error handling

constraint_handler_t

在头文件<stdlib.h>中定义

constraint_handler_t set_constraint_handler_s(constraint_handler_t handler);

(自C11以来)

配置要在运行时约束冲突时由所有边界检查函数调用的处理程序或恢复默认处理程序(如果handler是空指针)。

处理程序必须是指向类型函数的指针constraint_handler_t,该类型被定义为。

在头文件<stdlib.h>中定义

typedef void(* constraint_handler_t)(const char * restrict msg,void * restrict ptr,errno_t error);

(自C11以来)

在运行时约束冲突中,使用以下参数调用它:

1)指向描述错误的字符串的指针

2)指向实现定义的对象或空指针的指针。实现定义对象的示例是对象,该对象给出检测到违规的函数的名称以及检测到违规时的行号

3)调用函数返回的错误,如果它恰好是返回的函数之一 errno_t

如果set_constraint_handler_s是从来不叫,默认的处理程序是实现定义的:它可能是abort_handler_signore_handler_s或其他一些实现定义的处理程序。如同所有的边界检查功能,set_constraint_handler_s并且constraint_handler_t如果仅保证可供__STDC_LIB_EXT1__由实现所定义,并且如果用户定义__STDC_WANT_LIB_EXT1__的整数常数1,包括之前<stdlib.h>

参数

handler

-

指向constraint_handler_t类型的函数的指针或空指针

返回值

指向先前安装的运行时约束处理程序的指针。(注意:该指针永远不是空指针,因为调用会set_constraint_handler_s(NULL)设置系统默认处理程序)。

#define __STDC_WANT_LIB_EXT1__ 1
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
#ifdef __STDC_LIB_EXT1__
    char dst[2];
    set_constraint_handler_s(ignore_handler_s);
    int r = strcpy_s(dst, sizeof dst, "Too long!");
    printf("dst = \"%s\", r = %d\n", dst, r);
    set_constraint_handler_s(abort_handler_s);
    r = strcpy_s(dst, sizeof dst, "Too long!");
    printf("dst = \"%s\", r = %d\n", dst, r);
#endif
}

可能的输出:

dst = "", r = 22
abort_handler_s was called in response to a runtime-constraint violation.
 
The runtime-constraint violation was caused by the following expression in strcpy_s:
(s1max <= (s2_len=strnlen_s(s2, s1max)) ) (in string_s.c:62)
 
Note to end users: This program was terminated as a result
of a bug present in the software. Please reach out to your
software's vendor to get more help.
Aborted

参考

  • C11标准(ISO/IEC 9899:2011):
    • K.3.6/2 constraint_handler_t(p:604)
    • K.3.6.1.1 set_constraint_handler_s函数(p:604-605)

另请参阅

abort_handler_s(C11)

取消对边界检查函数的回调(函数)

ignore_handler_s(C11)

忽略边界检查函数的回调(函数)

C

C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。