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]
    

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

  • 相关阅读:
    API接口服务端
    phpredis扩展
    PHP之-json转数组,支持多层嵌套json
    瀑布流
    ERROR 1130: Host xxx is not allowed to connect to this MySQL server
    让IE支持CSS3 Media Query实现响应式Web设计
    Sublime Text快捷键:
    最简单的linux内存清理方法
    16: vue + crypto-js + python前后端加密解密
    16: mint-ui移动端
  • 原文地址:https://www.cnblogs.com/pure/p/2915554.html
Copyright © 2011-2022 走看看