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. And in the below program i have allocated appox 2040000(510000 x 4) bytes which is less than i limited ie,. 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.


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


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.


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.

链接地址: http://www.djcxy.com/p/80256.html

上一篇: 如何使用malloc()在redhat中分配比RAM更多的内存?

下一篇: 即使分配的内存少于ulimit限制,proc也会崩溃