Signal: Segmentation fault (11) in MPI C++
<p>I have a code, which counts the average value of integers in MPI:</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;time.h&gt;
#include &lt;mpi.h&gt;
#include &lt;assert.h&gt;

// Average method
int compute_avg(int *array, int num_elements) {
    int sum = 0;
    int i;
    for (i = 0; i &lt; num_elements; i++) {
    sum += array[i];
    }
    return sum / num_elements;
}

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

    if (argc != 2) {
    fprintf(stderr, "Usage: avg num_elements_per_proc\n");
    exit(1);
    }
    int num_elements_per_proc = atoi(argv[1]);

    MPI_Init(NULL, NULL);
    int world_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &amp;world_rank);
    int world_size;
    MPI_Comm_size(MPI_COMM_WORLD, &amp;world_size);

// Create array with integers
    int *nums = NULL;
    if (world_rank == 0) {

        for (int i =0; i&lt;5; i++){
            nums[i] = i;
        }
    }


// Subtable from any processes
    int *sub_nums = (int *)malloc(sizeof(int) * num_elements_per_proc);
    assert(sub_nums != NULL);


// distribution numbers for all processes
    MPI_Scatter(nums, num_elements_per_proc, MPI_INT, sub_nums,
    num_elements_per_proc, MPI_INT, 0, MPI_COMM_WORLD);

// Count avg subtable
    int sub_avg = compute_avg(sub_nums, num_elements_per_proc);

// Collectiong averages
    int *sub_avgs = NULL;
    if (world_rank == 0) {
    sub_avgs = (int *)malloc(sizeof(int) * world_size);
    assert(sub_avgs != NULL);
    }
    MPI_Gather(&amp;sub_avg, 1, MPI_INT, sub_avgs, 1, MPI_INT, 0, MPI_COMM_WORLD);


// Calculates the overall average
    if (world_rank == 0) {
    int avg = compute_avg(sub_avgs, world_size);
    printf("Avg of all elements is %d\n", avg);
// Obliczenie średniej na danych oryginalnych i wyświetlenie.
    int original_data_avg =
    compute_avg(nums, num_elements_per_proc * world_size);
    printf("Avg computed across original data is %d\n", original_data_avg);
}

// free memory
    if (world_rank == 0) {
    free(nums);
    free(sub_avgs);
    }
    free(sub_nums);
    MPI_Barrier(MPI_COMM_WORLD);
    MPI_Finalize();

return 0;
}
</code></pre>

<p>When i try to run this (<code>mpirun -c 4 avg 4</code>), i`m getting the error list:</p>

<blockquote>
  <p>[mangeke-mpi-2431940:03372] <strong>* Process received signal *</strong></p>
  
  <p>[mangeke-mpi-2431940:03372] Signal: Segmentation fault (11)</p>
  
  <p>[mangeke-mpi-2431940:03372] Signal code: Address not mapped (1)</p>
  
  <p>[mangeke-mpi-2431940:03372] Failing at address: (nil)</p>
  
  <p>[mangeke-mpi-2431940:03372] <strong>* End of error message *</strong></p>
</blockquote>

<p>How i can fix this problem?</p>