Segmentation Error Initializing Array

The following program produces a segmentation error, and I'm not sure why. mallocsucceeds, so it doesn't seem to be an initialization error, but for some reason it segfaults when I access element 253900. The array is only 4 * 1e6 bytes or about a megabyte.

This gives a lot of output.

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

int *long_array(size_t N) {
    int *arr = (int *) malloc(N);
    if (arr == NULL) { printf("could not malloc"); exit(1); }
    for (size_t i = 0; i < N; i++) {
        printf(".. %ld ", i);
        arr[i] =  10;
    }
    printf("done with loop\n");
    return arr;
}

int main(void) {
    int *arr = long_array(1000000);
    printf("%d", arr[5050]);
    return 0;
}

I compile this with gcc -std=c99and run the output to see the last few numbers printed before segfault:

253899 .. 253900 .. 2
segmentation fault (core dumped)  ./a.out

I do not understand why accessing a specific index causes a segmentation error. I can guess that I should access a memory location outside the address space of my processes, but this seems like an error if I successfully allocated memory from my address space.

+3
3

malloc(sizeof(int)*N) malloc(N). N , N .

+6

 int *arr = (int *) malloc(N * sizeof(int));
0

Your code is correct, but the problem is that you did not consider the size of an integer when allocating memory. You just highlighted:

int *arr=(int *)malloc(N);

here you just highlighted the size N, but you should consider the size of the integer on your computer. If you allocate only 10,000,000 the memory size and sizeof (int), then there is 4 on your computer, then it can just access the memory (10000000/4) ......... Therefore you need to allocate memory, for example:

int *arr=(int *)malloc(N*sizeof(int))

or

int *arr=(int *)malloc(N*sizeof(*arr));
0
source

All Articles