set_constraint_handler_s, constraint_handler_t
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    |   定义于头文件  <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,  | 
(C11 起) | |
运行时制约违规发生时,会按照以下参数调用它:
1) 指向描述错误的字符串的指针
2) 指向实现定义的对象的指针或空指针。实现定义对象的例子,是给出检测到违规的函数名和检测到违规时的行号的对象
3) 要由调用方函数返回的错误编号,若它正好是返回 
errno_t 的函数之一若从不调用 set_constraint_handler_s ,则默认处理是实现定义的:它可以是 abort_handler_s 、 ignore_handler_s 或另外的实现定义处理函数。
- 同所有边界检查函数, 
set_constraint_handler_s, constraint_handler_t仅若实现定义了 __STDC_LIB_EXT1__ ,且用户在包含<stdlib.h>前定义 __STDC_WANT_LIB_EXT1__ 为整数常量 1 才保证可用。 
参数
| 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 standard (ISO/IEC 9899:2011):
 
- K.3.6/2 constraint_handler_t (p: 604)
 
- K.3.6.1.1 The set_constraint_handler_s function (p: 604-605)
 
参阅
|    (C11)  | 
   边界检查函数的异常中止回调   (函数)  | 
|    (C11)  | 
   边界检查函数的忽略回调   (函数)  |