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

谁说胖子不能爱 提交于 2019-12-25 04:39:21

问题


I have set stack size to 2000Kb by ulimit -s 2000 and ulimit -Ss 2000 for hard limit. And in the below program i have allocated appox 2040000(510000 x 4) bytes which is less than i limited i.e,. 2048000(2000*4)bytes but i see that my program crashes! 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. This happens only when i limit by ulimit.


回答1:


int a[510000] will be an array with index from 0 to 509999. a[510000] is outside the array range.




回答2:


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!!").

Remember, C uses 0-based array indexing.




回答3:


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.



来源:https://stackoverflow.com/questions/31271742/proc-crashes-even-if-it-allocates-less-memory-than-limited-by-ulimit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!