一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述

栏目: Go · 发布时间: 7年前

内容简介:在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。

背景

在递归处理的调用中,在具体的工程实践中一般会引入递归深度检测,防止因为错误的数据造成系统的资源极大的消耗,本方法定义了一种通用简单的递归检查方法。

步骤

实现函数 RecursiveDepthChecker

func RecursiveDepthChecker(max int) bool {
    //注意,这里我们跳过了本函数自己的栈,找到父调用的函数名
    caller, _, _, _ := runtime.Caller(1)
    currentFuncName := runtime.FuncForPC(caller).Name()
    stack := make([]byte, 65535*1) //max 1MB stack traceback
    //由于Golang Runtime中很多关于栈的函数未导出,无法使用。因此使用最肮脏的字符串检测方法
    runtime.Stack(stack, false)
    start := 0
    depth := 0
    for {
        count := strings.Index(string(stack[start:]), currentFuncName)
        if count >= 0 {
            start += count + len(currentFuncName)
            depth++
        } else {
            break
        }
    }

    if depth > max {
        return false
    }
    return true
}

在需要进行检测的函数用引入检查即可

func TFunc() {
    fmt.Println("Start Caller...")
    if !RecursiveDepthChecker(5) {
        fmt.Println("Stack Overflow")
        return
    }
    TFunc()
}

以上所述就是小编给大家介绍的《一种通用递归深度检测技术 - 基于栈帧内容的检测 - Golang语言描述》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Agile Web Application Development with Yii 1.1 and PHP5

Agile Web Application Development with Yii 1.1 and PHP5

Jeffrey Winesett / Packt Publishing / 2010-08-27

In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器