简体   繁体   English

即使Proc分配的内存少于ulimit限制,它也会崩溃

[英]Proc crashes even if it allocates less memory than limited by ulimit

I have set stack size to 2000Kb by ulimit -s 2000 and ulimit -Ss 2000 for hard limit. 我已将ulimit -s 2000和ulimit -Ss 2000的堆栈大小设置为2000Kb进行硬限制。 And in the below program i have allocated appox 2040000(510000 x 4) bytes which is less than i limited ie,. 并且在下面的程序中,我分配了约小于我限制(即)的appox 2040000(510000 x 4)字节。 2048000(2000*4)bytes but i see that my program crashes! 2048000(2000 * 4)bytes,但是我看到程序崩溃了! Can anybody suggest why this happens. 有人可以建议为什么会这样。

#include <stdio.h>
#include <malloc.h>
int main()
{
    int a[510000] = {0};
    a[510000] = 1;
    printf("%d", a[510000]);
    fflush(stdout);
    sleep(70);
}

EDIT 1: Crash is not because of the array index out of bound as i tried lower index and still crashes. 编辑1:崩溃不是因为数组索引超出范围,因为我尝试使用较低的索引仍然崩溃。 This happens only when i limit by ulimit. 仅当我通过ulimit限制时,才会发生这种情况。

The problem here is, in below mentioned statements 问题是,在下面提到的语句中

  a[510000] = 1;
  printf("%d", a[510000]);

you're having off-by-one index. 您拥有的是一对一的索引。 The above statements are accessing array out of bounds. 上面的语句超出范围访问数组。 This in turn invokes undefined behaviour . 反过来,这会引发未定义的行为 One of the side effects of UB, other than getting a nasal demon is segmentation fault (The "Crash!!"). 得到鼻恶魔外 ,UB的副作用之一是分割错误(“崩溃!”)。

Remember, C uses 0 -based array indexing. 请记住, C使用基于0的数组索引。

int a[510000] will be an array with index from 0 to 509999 . int a[510000]将是索引从0509999的数组。 a[510000] is outside the array range. a[510000]在数组范围之外。

You're corrupting the stack in 您正在破坏堆栈

a[510000] = 1;

because the last index in that array is one less than 510000. So that assignment overwrites data on the stack and once other statements try to use that data your application crashes. 因为该数组中的最后一个索引小于510000。因此,该赋值将覆盖堆栈中的数据,并且一旦其他语句尝试使用该数据,应用程序就会崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM