0

I am new to c programming. I have a program which tests how much time does it take to compute a series of 3 nested loop and calculation inside it whenever i try to run this code it causes segmentation fault. Here is the code and debug info:

#include <stdio.h>
#include <sys/time.h>
#define EXIT_SUCCESS 0;

int main(void){
  struct timeval start,end;
  gettimeofday(&start, NULL);
  int n = 100;
  int sum[n][n][n];
  int firstNum[n][n][n];
  int secondNum[n][n][n];
  for(size_t a=0;a<n;a++){
    for (size_t b = 0;b<n;b++){
      for (size_t c=0;c<n;c++){
        firstNum[a][b][c] = c;
        secondNum[a][b][c] = 1;
        sum[a][b][c] = firstNum[a][b][c] + secondNum[a][b][c];
      }
    }
  }
  gettimeofday(&end, NULL);
  double timeTook = (end.tv_sec - start.tv_sec)*1000.0;
  printf("Time took: %f\n", timeTook);
  return EXIT_SUCCESS;
}

Debug info

Program received signal SIGSEGV, Segmentation fault.
main () at /home/ayush/Desktop/Project/trial.c:16
16              secondNum[a][b][c] = 1;

I want to know what is causing this error I am accessing the arrays index within the memory bound but it still causes segmentation fault.

Programmerabc
  • 329
  • 2
  • 10
  • 1
    The Variable Length Arrays (VLA) `int sum[n][n][n]` (with `n = 100`) are too large for your implementation to deal with. Try `malloc()` (and `free()`). ... `int (*sum)[n][n] = malloc(n * sizeof *sum); // replacing int sum[n][n][n];` – pmg Jul 18 '21 at 17:05
  • Thanks @pmg `int (*sum)[n][n] = malloc(n*sizeof *sum)` solved my problem – Programmerabc Jul 18 '21 at 18:05
  • Depends on what you use to compile. MSVC has the /STACK option. Default stack size is 1MB. But for your problem, this is not the solution. – lulle2007200 Jul 18 '21 at 18:06
  • @lulle you are right i didn't find anything useful about this problem using compiler flag but instead **_malloc()_** got the job done – Programmerabc Jul 18 '21 at 18:09

1 Answers1

1

In the code shown

 int n = 100;
 int sum[n][n][n];

sum is a Variable Length Array (VLA). Depending on your implementation, the size available for VLAs (the stack) can be very limited (usually 1M, the array requires 4M, 3 arrays require 12M).

One easy solution to (kinda) still use VLAs but getting memory from a larger space (the heap) is to replace the array definitions with pointers and allocate enough memory.

int n = 100;
int (*sum)[n][n]; // sum is a pointer to n*n arrays (kinda using VLAs)
sum = malloc(n * sizeof *sum); // allocate space for n items of n*n elements
if (sum == NULL) exit(EXIT_FAILURE); // exit if allocation failure
//...
//use sum as if it was defined as sum[n][n][n]
//...
free(sum);
pmg
  • 106,608
  • 13
  • 126
  • 198