# 撸码

今天研究算法时需要用到一个很大的数组,代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    uint16_t list[100000000] = {0};
    printf("OK\n");

    return EXIT_SUCCESS;
}

数组大小为 2字节 * 100,000,000 ≈ 200M字节

# 运行报错

运行

liyongjun@Box:~/project/my/c/study$ ./stack.out 
段错误 (核心已转储)

😰

# 找问题

liyongjun@Box:~/project/my/c/study$ free -h
              total        used        free      shared  buff/cache   available
Mem:           7.8G        2.2G        1.4G         46M        4.2G        5.2G
Swap:          974M        268K        974M

剩余内存够用。难道是因为剩余内存总量够,但不是连续的,没办法分配一个200M的连续内存空间?

网上搜索linux C语言内存申请限制,最终确定问题原因:linux C程序申请堆栈空间受ulimit -s参数限制,一般默认为8192Kbytes

liyongjun@Box:~/project/my/c/study$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 31666
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 8192
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 31666
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
liyongjun@Box:~/project/my/c/study$ ulimit -s
8192

# 解决

将堆栈空间增加到200,000Kbytes,程序成功运行

liyongjun@Box:~/project/my/c/study$ ulimit -s 200000
liyongjun@Box:~/project/my/c/study$ ./stack.out 
OK

😄