1

i am getting segmentation fault while writing data into file. here is code

 int arr[N]; // where N = 1508065

f = fopen( "datafile.txt", "w" );

if (f == NULL)

{

    printf("Error opening file!\n");
    exit(1);
}

for( i=1;i<=N;i++)

    {
       arr[i]=rand()%100;
       fprintf(f, "%d  %d  %d\n",i,1,arr[i] );
    } 

fclose(f); 

I have tried with double arr[N] even then is a segmentation fault. It works fine when N is small.

user2736738
  • 30,591
  • 5
  • 42
  • 56
Mani
  • 51
  • 10

3 Answers3

2

for( i=1;i<=N;i++) will give undefined behavior.

C arrays start at 0 and go to N-1. Accessing element N is a no-no.

Should be for( i=0;i<N;i++)

John3136
  • 28,809
  • 4
  • 51
  • 69
1

Accessing the N-th index of a N-size array is undefined behavior. You are accessing array out of bound. It will be for( i = 1; i < N; i++).

From standard: J.2 Under Undefined Behavior

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a1[7] given the declaration int a[4][5])

As you were using - arrays are 0 indexed in .

user2736738
  • 30,591
  • 5
  • 42
  • 56
1

It works fine when N is small.

I suppose you create arr as local variable, for N = 1508065 it is more than 5 MB memory allocated onto stack - you got stack overflow. You should allocate arr using malloc function or create this array as global variable.

Problem with reading out of range was pointed out in previous answers.

rafix07
  • 20,001
  • 3
  • 20
  • 33