Segmentation Fault on Large Array Sizes

Huge array is causing segmentation fault [duplicate]

You're probably blowing your stack. For anything "big" allocate dynamically using something like calloc:

int main()
{
int L = 10000000;
float *array = calloc(L, sizeof(float));

FILE *fp;
fp = fopen("datafile.txt",'r');
/*
reading values into the array from datafile.txt using fscanf
and doing some operations on array elements
*/
fclose(fp);

free(array);
return 0;
}

Local variables are limited in size, so trying to create a local variable that's "too big" will result in unpredictable behaviour or even crashes. The memory remaining for local variables depends on how deeply nested your code is, so it can fluctuate wildly. This is why keeping your local variables to a minimum is important. Pointers and integers are really cheap, but arrays of a consequential size are trouble.

Segmentation Fault when dealing with large array size

for(i;i<i+CHUNK;i++)

Since i will always be less than i + CHUNK (unless it overflows), this loop will overrun the bounds of the array.

C segmentation fault with very large array at specific indices

the following code

  1. compiles cleanly
  2. performs the appropriate error checking
#include <stdlib.h>
#include <stdio.h>


#define WIDTH (1000)
#define HEIGHT (1000)


/////////////////////////////////////////////////////////
// Program main
/////////////////////////////////////////////////////////

int main( void )
{

// set seed for rand()
srand(2006);

// 1. allocate host memory for matrices A and B
unsigned int length = WIDTH * HEIGHT;
unsigned int size = sizeof(int) * length;

printf("%u\n", size);
int* matrixA = NULL;
if( NULL == (matrixA = malloc(size) ) )
{// then malloc failed
perror( "malloc failed");
exit( EXIT_FAILURE );
}

// implied else, malloc successful

for(unsigned i = 0; i < length; i++)
{
printf("%i\n", i);
matrixA[i] = rand() % 10;
}

free(matrixA);
} // end function: main

Segmentation Fault, large arrays

You are overflowing the stack. 2 * 1024 * 1024 * sizeof(int) is a lot for most systems.

The simplest solution would be to make the arrays static.

static int a[N][N];
static int b[N][N];

Other methods:

  • Make the arrays global (this is essentially the same as the above)
  • Use malloc in a loop and of course remember to free

    int **a = malloc(N * sizeof *a);
    for (i = 0; i < N; i++)
    a[i] = malloc(N * sizeof *a[i]);

Segmentation Fault in C when adding an element to array

The array x is of length 1,000, but you're treating it in the loop as if it's of length 10,000. Accessing x[i] for i greater than or equal to 1,000 is undefined behaviour because the index is out of the array's range.

Thus, a segmentation fault is occurring because your program is accessing memory that it is not allowed to access.



Related Topics



Leave a reply



Submit