非常教程

C参考手册

错误处理 | Error handling

abort_handler_s

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

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

(自C11以来)

写入一个实现定义的消息,stderr其中必须包含指向的字符串msg和调用abort()

可以将指向此函数的指针传递给set_constraint_handler_s以建立运行时约束违规处理程序。与所有边界检查的函数一样,abort_handler_s只有__STDC_LIB_EXT1__在实现定义并且用户在包含之前定义__STDC_WANT_LIB_EXT1__为整数常量时1才能保证可用<stdlib.h>

参数

msg

-

指向写入标准错误流的消息的指针

ptr

-

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

error

-

errno_t类型的正值

返回值

没有; 这个函数不会返回给调用者。

注意

如果set_constraint_handler_s是从来不叫,默认的处理程序是实现定义的:它可能是abort_handler_signore_handler_s或其他一些实现定义的处理程序。

示例

#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.1.2 abort_handler_s函数(p:605)

另请参阅

ignore_handler_s(C11)

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

set_constraint_handler_s(C11)

为边界检查函数(函数)设置错误回调

C

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