The code bellow sometimes throws exceptions similar to:
Exception thrown at 0x779CC19E (ntdll.dll) in Matriks.exe: 0xC0000005: Access violation reading location 0x0000001D.
I'm new to C and just learned to use pointers. Any tips ? Are there other problems in my code that are worth criticizing ?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main()
{
int *Matrix_01, *Matrix_02;
int a, b, i, n,valid=1;
srand(time(0));
do
{
printf("Insert number of rows: ");
scanf("%d", &a);
printf("Insert number of columns: ");
scanf("%d", &b);
if (a >= 0 && b >= 0)
valid = 0;
else
{
printf("Invalid input!");
system("pause>null & cls");
}
} while (valid == 1);
Matrix_01 = (int *)malloc(a * b * sizeof(int));
Matrix_02 = (int *)malloc(a * b * sizeof(int));
for (i = 0; i < a; i++)
for (n = 0; n < b; n++)
{
Matrix_01[a*i + n] = rand() % 50;
Matrix_02[a*i + n] = rand() % 50;
}
printf("\nFirst Matrix:\n");
for (i = 0; i < a; i++)
{
printf("\n");
for (n = 0; n < b; n++)
{
printf("%4d", Matrix_01[a*i + n]);
}
}
printf("\n\nSecond Matrix:\n");
for (i = 0; i < a; i++)
{
printf("\n");
for (n = 0; n < b; n++)
{
printf("%4d", Matrix_02[a*i + n]);
}
}
printf("\n\nAddition:\n");
for (i = 0; i < a; i++)
{
printf("\n");
for (n = 0; n < b; n++)
{
printf("%4d", Matrix_01[a*i + n]+Matrix_02[a*i + n]);
}
}
printf("\n\nSubtraction:\n");
for (i = 0; i < a; i++)
{
printf("\n");
for (n = 0; n < b; n++)
{
printf("%4d", Matrix_01[a*i + n] - Matrix_02[a*i + n]);
}
}
printf("\n");
system("pause>null");
}
Heap is corrupt in that case means that you wrote out of the valid allocated zones.
Check the min & max values of your index:
i
ranges from 0
to a-1
n
ranges from 0
to b-1
So a*i + n
ranges from 0
to a*(a+1) + b
. So it doesn't match the matrix dimensions. If a
is bigger than b
the memory will get corrupted.
You need to replace this by b*i + n
(which ranges from 0
to b*(a-1) + b
=> a*b
You also want to avoid to allow that a
or b
is zero when reading the input. Actually, it's better to check if scanf
succeeded in scanning one value by checking the return code then check if values are greater than zero (but not equal)
Or use 2D matrixes (or compute pointers on rows once to avoid those computations)
User contributions licensed under CC BY-SA 3.0