zoukankan      html  css  js  c++  java
  • Stack overflow

    In software, a stack overflow occurs when too much memory is used on the call stack. The call stack contains a limited amount of memory, often determined at the start of the program. The size of the call stack depends on many factors, including the programming language, machine architecture, multi-threading, and amount of available memory. When a program attempts to use more space than is available on the call stack (that is, when it attempts to access memory beyond the call stack's bounds, which is essentially a buffer overflow), the stack is said to overflow, typically resulting in a program crash.

    int foo() {
         return foo();
    }
    int foo() {
         double x[1000000];
    }

    递归和申请本地变量过大都容易引起栈溢出,须警惕。

    Detail:Stack overflow(wiki)

    举个例子:

    #include <stdio.h>
    int main() {
        const int stackMaxSize = 1024 * 1024 * 50;   // 50M
        char buf[stackMaxSize];
        printf("run no error!\n");
        return 0;
    }

    运行结果:崩溃。

    bash: line 1:  1814 Segmentation fault: 11  '/Users/yuming/Downloads/test'
    [Finished in 0.3s with exit code 139]
    

    稍作修改,改为在堆上申请内存

    #include <stdio.h>
    int main() {
        const int stackMaxSize = 1024 * 1024 * 50;   // 50M
        char* buf = new char[stackMaxSize];
        delete []buf;
        printf("run no error!\n");
        return 0;
    }

    运行结果:正常。

    run no error!
    [Finished in 0.1s]
    

    题外话:栈溢出漏洞很容易被入侵哦,大家小心为上。  

  • 相关阅读:
    jQuery ajax传多个参数
    PHP 上传图片和安全处理
    PHP CI框架email类发送邮件
    2016-4-7
    jquery 轮播图
    CI控制器的继承问题
    2016-4-1
    2016-3-31 总结
    php内置函数call_user_func()
    discuz-目录
  • 原文地址:https://www.cnblogs.com/pure/p/2915554.html
Copyright © 2011-2022 走看看