Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault initialising an array

Tags:

c

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

This does produce 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=c99 and run the output to see the final few numbers printed before the segfault:

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

I don't understand why accessing a particular index is causing the segmentation fault. I can guess that I must be accessing a memory location outside of my processes address space, but this seems like a bug if I successfully allocated the memory from within my address space.

like image 745
Charles Avatar asked Jun 23 '26 20:06

Charles


1 Answers

malloc(sizeof(int)*N) instead of malloc(N). Otherwise you'd get an array of N bytes, not N integers.

like image 173
Moshe Gottlieb Avatar answered Jun 25 '26 11:06

Moshe Gottlieb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!