scrblnrd3
scrblnrd3

Reputation: 7416

C segmentation fault with very large array at specific indices

I have a program that deals with very large arrays, and when I'm trying to populate the array with random values, it always segfaults at a specific index. On Mac OSX 10.10 running XCode, it segfaults at index 1000448, and on GCC targeting LLVM version 6.1.0 it faults at 1001472.

Here is my code

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


#define WIDTH 1000
#define HEIGHT 1000


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

int main(int argc, char** argv) {

    // 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("%i", size);
    int* matrixA = (int*) malloc(size);
    for(int i = 0; i < size; i++) {
        printf("%i\n", i);
        matrixA[i] = rand() % 10;
    }

    free(matrixA);
}

Why is this segfaulting? I checked the size allocated to matrixA, and it appears to be the correct size (4,000,000)

Upvotes: 1

Views: 637

Answers (2)

user3629249
user3629249

Reputation: 16540

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

Upvotes: 2

scrblnrd3
scrblnrd3

Reputation: 7416

Oops, I just realized what the problem was. I'm looping from 0 to size, instead of length. If someone could tell my why those particular values, though, it would be great

Upvotes: 1

Related Questions