-2

I have declared the following:

  1. long long int *a[100000] //Global Declaration

  2. Dynamic declaration of a[i]:

    a[i]=(long long int*)calloc(sizeof(long long int),100000);
    
    for(i=0;i<100000;i++) {
       for(j=0;j<100000;j++)
           printf("%lld ",a[i][j]);
           printf("\n");
    }
    

After going through the loop my program is showing segmentation fault

Because of I'm getting right answer of some of the test cases and segmentation fault of some other test cases it means I am not accessing illegal memory. I think The problem is with the declaration of an array of long long int of such larger size.

sansuiso
  • 9,259
  • 1
  • 40
  • 58
Aniruddha Paul
  • 119
  • 1
  • 10

3 Answers3

0

Note the definition of 2d array and allocation of it's elements:

#include <stdio.h>
#include <stdlib.h>
int main(void) {
    long long int* a[10][10]; //AS I MENTIONED IN THE COMMENT UNDER THE QUESTION
    int i, j;
    for(i=0;i<10;i++) {
       for(j=0;j<10;j++) {
           a[i][j] = calloc(sizeof(long long int),10);
       }
    }
    for(i=0;i<10;i++) {
       for(j=0;j<10;j++)
           printf("%lld ",a[i][j]);
           printf("\n");
    }
    return 0;
}

And also note that, according to your version, you'll try to allocate 100000x100000x100000 bytes of RAM (quadrillion bytes??).

simurg
  • 1,208
  • 7
  • 14
0

Assuming the 2nd snippet you show is inside a loop k = 0 to 100000-1 you do not want to address 100000x100000 elements of a inside this loop as obviously only 100000 x k elements had been allocated so far.

Doing so would address invalid memory for all a[i][j] with j > k, invoking undefined behaviour with this.

To fix this limit printing to the column just allocated:

#define ARRAY_SIZE (100000)

...

long long int * a[ARRAY_SIZE] //Global Declaration

for (size_z k = 0; k < ARRAY_SIZE; ++k)
{
  a[k] = calloc(sizeof * a[k], ARRAY_SIZE);
  if (NULL == a[k])
  {
    perror("calloc() failed);
    exit(1);
  }

  for (size_t j = 0; j < ARRAY_SIZE; ++j)
  {
    printf("%lld ", a[k][j]);
  }

  printf("\n");
}

Changes:

  • In C casting the result of malloc() & friends is not necessary, nor recommended. Do not do it.
  • The preferred type to index arrays is size_t.
  • Always test the outcome of all relevant function calls.
  • Don't repeat yourself and do not use magic numbers. So define all constants using self-explanory #defines or consts.
alk
  • 69,737
  • 10
  • 105
  • 255
-1

Why dont you initialize like long long int a[100000][100000] ? Too large?

I am afraid that this way you puzzle the compiler, because the a[i][j] is a way you select from bidimensional array. Did you try to define long long int *p ?

long long int *p
//... and in the loop
p=a[i];
printf("%lld",p[j]);

edit: do you have enough of ram+swap? For me it is 80GB to allocate.

jaromrax
  • 274
  • 1
  • 12