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]
    

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

  • 相关阅读:
    使用定时器实现获取手机验证码倒计时
    搜索历史管理
    利用vue和jQuery实现中国主要城市搜索与选择
    使用vue、jQuery生成带有logo的二维码
    使用vue-cli脚手架搭建Vue项目
    postcss-px-to-viewport
    git命令操作篇
    小程序中live-player
    对于常用数组的方法总结
    css的加载中动画
  • 原文地址:https://www.cnblogs.com/pure/p/2915554.html
Copyright © 2011-2022 走看看