P
P
Pavel Sklyar2018-09-06 11:09:51
C++ / C#
Pavel Sklyar, 2018-09-06 11:09:51

How to fix segmentation error in C?

I have a two-dimensional dynamic array, consisting, for example, of 2 rows and 3 columns:
1 2 3
4 5 6
The essence of the task: flip our original array by 90 degrees, that is, in our case, make an array of 3 rows and 2 columns:
4 1
5 2
6 3

#include <stdio.h>
#include <stdlib.h>

int main() {
    
    int N, M;
    int **array;
    int **newArray;

    printf("Введите числа N и M: ");
    scanf("%d %d", &N, &M);

    array = (int **)malloc(N * sizeof(int));
    for (int i = 0; i < N; i++) {
        array[i] = (int *)malloc(M * sizeof(int));
    }

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            printf("array[%d][%d] = ", i, j);
            scanf("%d", &array[i][j]);
        }
    }

    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            printf("%d ", array[i][j]);
        }
        printf("\n");
    }
    printf("\n");

    newArray = (int **)malloc(M * sizeof(int));
    for (int i = 0; i < M; i++) {
        newArray[i] = (int *)malloc(N * sizeof(int));
    }

    printf("%d %d \n", M, N);
    for (int i = 0; i < M; i++) {
        int n2 = N - 1;
        for (int j = 0; j < N; j++) {
            newArray[i][j] = array[n2][i];
            printf("%d ", newArray[i][j]);
            n2--;
        }
        printf("\n");
    }

}

Filling the first array with the above parameters occurs without problems, the second array is also quietly filled at first, but a segmentation fault 11 occurs on the 3rd line of the new array. If I put 3 rows and 2 columns into the original array, then the same error occurs after filling 5 6 cells.
If I allocate 2 times more memory for both arrays, everything works fine.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alex_fedorov, 2018-09-06
@pavelsklyar

Mistake #1
array = (int **)malloc(N * sizeof(int));
newArray = (int **)malloc(M * sizeof(int));
Here you must allocate an array of pointers, not an array of ints. Those. should be

array = (int **)malloc(N * sizeof(int*));
newArray = (int **)malloc(M * sizeof(int*));

Mistake #2
Memory needs to be freed after use

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question