Access violation writting location error when calculating the transpose of a matrix

0

I have written a code which calculates the transpose of a matrix NxM using double pointers.
As long as the matrix is square(NxN) it works without problems, but if it isn't, I get this error:

Exception thrown at 0x00052580 in ConsoleApplication27.exe: 0xC0000005: Access violation writing location 0xFDFDFDFD. If there is a handler for this exception, the program may be safely continued.

Here is my code:

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

int **alloc(int r, int c) {
    int **d;

    d = (int **)malloc(r * sizeof(int *));
    for (int i = 0; i < r; i++) {
        d[i] = (int *)malloc(c * sizeof(int));
    }
    return d;
}

void input(int **A, int r, int c) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            printf("[%d][%d]=", i, j);
            scanf("%d", &A[i][j]);
        }
    }
}

void output(int **A, int r, int c) {
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            printf("%d ", A[i][j]);
        }
        printf("\n");
    }
}
void transpose(int **A, int r, int c) {
    int **T = alloc(r, c);
    int i, j;
    for (i = 0; i < r; i++)
        for (j = 0; j < c; j++)
            T[j][i] = A[i][j];
    output(T, c, r);
}

void main()
{
  int r,c;
  scanf("%d%d",&r,&c);
  int **A=alloc(r,c);
  input(A, r, c);
  printf("The transpose of the matrix is: \n");
            transpose(A, r, c);
}

Could you point and fix my error for me? I've run this in Visual Studio 2015 and I get that error, and on https://www.onlinegdb.com I get Segmentation fault (core dumped)

c
pointers
matrix
error-handling
segmentation-fault
asked on Stack Overflow Jan 31, 2021 by Dohn Joe • edited Jan 31, 2021 by IrAM

1 Answer

1
int **T = alloc(r, c);

I'd start by looking at the line of code shown above. If you're transposing an RxC matrix, you probably want the target to be CxR. Otherwise, you're likely to run off the end of one of the dimensions.

Anything beyond that, you probably want to learn to use the debugger, which is particularly good in Visual Studio. Single-stepping through the code and keeping an eye on the relevant variables is a valuable skill to learn.


As an aside, there are two other things that can cause problems with your code:

  • In C, you should not cast the return value from memory allocation functions, that can introduce certain subtle errors; and
  • You should check the return value of memory allocation functions to ensure they haven't failed.

Neither of those are very likely in this case, unless your matrices are massive, but it's a good habit to get into.

answered on Stack Overflow Jan 31, 2021 by paxdiablo • edited Jan 31, 2021 by paxdiablo

User contributions licensed under CC BY-SA 3.0