title: Why do I get a segmentation fault when trying to copy an array from stdin to a 2d array?
body: <p>This is in relation to the HackerRank Restaurant problem, which I have solved in other languages but am trying, now, to solve in C.<a href="https://www.hackerrank.com/challenges/restaurant" rel="nofollow">https://www.hackerrank.com/challenges/restaurant</a></p>
  
  <p>I first tried to store the result if <code>read_slice_dimension()</code> directly into the multidimensional array, but because I cannot pass an array back from a function without making it static, this does not work because then every nested array points to the same static 2 integer array in memory, which, as a result of it being overwritten every time <code>read_slice_dimension()</code> is called, means I would have an array containing <code>num_slices</code> pointers to the last array read in from stdin.</p>
  
  <p>Thus my decision to try <code>memcpy</code>, so that I could copy the arry from <code>read_slice_dimension()</code> to a new block of memory so that it persists and is not lost when I read in the next slice.  It appears, however, that <code>memcpy</code> is not the way to do this.  What is?</p>
  
  <pre><code>// Gets the number of slices for this test according to the first input value from stdin.
  int read_num_slices() {
    int num_slices = 0;
  
    scanf("%i", &amp;num_slices);
  
    if (num_slices == 0) {
      goto error;
    }
  
    return num_slices;
  
  error:
    flag_error("ERROR: Could not parse the number of entries from first input line.");
  }
  
  // Gets a single line from stdin and attempts to parse it into a 2D int array representing the dimensions of a slice.
  int* read_slice_dimension() {
    static int slice_dimension[2] = {0};
  
    scanf("%i %i", &amp;slice_dimension[0], &amp;slice_dimension[1]);
  
    if (slice_dimension[0] + slice_dimension[1] == 0) {
      goto error;
    }
  
    return slice_dimension;
  
  error:
    flag_error("ERROR: Could not parse line entered into a 2 integer array representing the slice's dimensions.");
  }
  
  // Gets all of the bread slices to be processed.
  //
  // This function reads from stdin.  The first line should be a single integer that specifies the number of slices to be
  // processed by this current test.  The subsequent lines should be two integers separated by a space which represent
  // the 2D dimensions of each slice.
  int** get_slices() {
    int num_slices = read_num_slices();
    static int** slices;
    slices = (int**)malloc(num_slices * sizeof(int*));
  
    int i = 0;
    for (i; i &lt; num_slices; i++) {
      int* slice = slices[i];
      slice = (int*)malloc(2 * sizeof(int));
      memcpy(slice, read_slice_dimension(), 2 * sizeof(int));
      printf("%i %i\n", slices[i][0], slices[i][1]); // CAUSES SEGMENTATION FAULT
    }
  
    return slices;
  }
  </code></pre>