Array index limit in C

On Linux with 16x RAM, why the following segfault:

#include <stdlib.h>

#define N 44000

int main(void) {
    long width = N*2 - 1;
    int * c = (int *) calloc(width*N, sizeof(int));
    c[N/2] = 1;
    return 0;
}

According to GDB, the problem is from c [N / 2] = 1, but what is the reason?

+3
source share
7 answers

You allocate about 14-15 GB of memory and for some reason the allocator cannot give it to you at the moment, so it callocreturns NULL, and you are segfault, because you are casting a NULL pointer.

Check if calloc returns NULL.

Suppose you are compiling a 64-bit program under 64-bit Linux. If you do something else - you can overflow the calculation to the first argument before calloc, if the long one is not 64 bits in your system.

For example, try

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

#define N    44000L

int main(void)
{
    size_t width = N * 2 - 1;
    printf("Longs are %lu bytes. About to allocate %lu bytes\n",
           sizeof(long), width * N * sizeof(int));
    int *c = calloc(width * N, sizeof(int));
    if (c == NULL) {
        perror("calloc");
        return 1;
    }
    c[N / 2] = 1;
    return 0;
}
+4
source

, calloc NULL.

, calloc/malloc/realloc. , .

+6

32- , "". size_t long. , .

+6

2.6 (, - 14 64-... 2.6 nbsp; 32 ). -, Linux , calloc() .

Mac OS X X 32 64 , (, , dyld ).

, , dandy 64 ( 32- , ).

; " " / . , , .

+2

, #define :

#define N    44000L

, . calloc.

calloc null, .

+2

14 GB .

+1
source

The donut dollars calloc()returned NULL because it could not satisfy the request, so an attempt to respect c caused segfault. You should always check the result *alloc()to make sure it is not NULL.

+1
source

Source: https://habr.com/ru/post/1716818/


All Articles