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)
Related
How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div 4):
(Problem) Chef has an array A of length N. Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .
Determine the minimum possible value of X. If no possible value of X exists, output -1.
Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int* binary_number(int n) // returns pointer to a array of length 20(based on given constrains) representing binary
{
int* ptc;
ptc = (int*) malloc(20*sizeof(int));
for(int i = 0; i < 20; i++)
{
if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
else {*(ptc + i) = 0;}
n = n % (int) pow(2,19-i) ;
}
return ptc;
}
int or_value(int* ptc, int n) // Takes in pointers containing 1 or zero and gives the logical OR
{
for(int k = 0; k < n; n++)
{
if(*ptc == *(ptc + 20*k)){continue;} // pointers are 20 units apart
else{return 1;break;}
}
return *ptc;
}
int main(void) {
int t; scanf("%d", &t);
for (int i = 0; i < t; i++)
{
int n, y;
scanf("%d %d", &n, &y);
int a[n];
for(int j = 0; j < n ; j++)
{
scanf("%d", &a[j]);
}
int b[20*n];
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 20; k++)
{
b[20*j + k] = *(binary_number(a[n])+k);
}
}
int c = 0;
int p = 0;
for (int j = 0; j < 20; j++)
{
if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
}
if (p==1){printf("-1");}
else {printf("%d\n", c);}
}
return 0;
}
In line 10 I cannot find out where my problem is at first. I place int a[100][100]={0} but the cpu speed is stuck.
Then, I try to change it into a[n][n] but no output is shown.
Last, I try to change it again as if it resembles the original ones.
However, nothing works instead of a new question.
#include<stdio.h>
int main() {
int n;
while (scanf("%d", &n)) {
n *= 2;
int x = 0, y = 0, num = 1;
int a[n][n] = {0};
a[x][y] = num++;
while (n * n >= num) //定義陣列
{
while (y + 1 < n && !a[x][y + 1]) //向右
a[x][++y] = num++;
while (x + 1 < n && !a[x + 1][y]) //向下
a[++x][y] = num++;
while (y - 1 >= 0 && !a[x][y - 1]) //向左
a[x][--y] = num++;
while (x - 1 >= 0 && !a[x - 1][y]) //向上
a[--x][y] = num++;
}
for (x = 0; x < n; x++) //print 陣列
{
for (y = 0; y < n; y++) {
if (y != n - 1) {
printf("%d ", a[x][y]);
} else {
printf("%d", a[x][y]);
}
}
printf("\n");
}
break;
}
return 0;
}
At least this problem:
Variable Length Arrays (VLA) cannot be initialized via the C standard.
Alternate, assign via memset() after defining a.
// int a[n][n]={0};
int a[n][n];
memset(a, 0, sizeof a);
i am using 4 for lopp , 2 are working correct rest 2 are showing issue 3 and 4 loop are showing invalid answer:
#include <stdio.h>
int main(void) {
// your code goes here
int n,arr[n],i,l=0,m=0,u=0,d=0;
printf("enter the value of n");
scanf("%d",&n);
arr[0]=0;
for(i=0;i<n;i++) {
arr[i+1]=arr[i]+10;
}
printf("%d",arr[3]);
for(i=1;i<=n;i=i+4) {
l=arr[i]+l;
}
for(i=2;i<=n;i=i+4) {
u=arr[i]+u;
}
for(i=3;i<=n;i=i+4) {
m=arr[i]+m;
}
/* for(i=4;i<=n;i=i+4) { d=arr[i]+d; } */
printf("\n%d\n",l);
printf("%d\n",u);
printf("%d\n",m);
printf("%d\n",d);
return 0;
}
answer in negative
Among the things wrong in this code
Your decl of arr[n] is based on an indeterminate n value. The array doesn't magically resize when you read n later in your program. n has to be known before the arr decl.
Your loop limits are potentially out of range (and definitely with the first loop).
The scanf call to populate n isn't checked for successful stdin input. Never assume your IO works, especially the 'I' in IO.
Just fixing those:
#include <stdio.h>
int main(void)
{
int n, i, l = 0, m = 0, u = 0, d = 0;
printf("enter the value of n");
if (scanf("%d", &n) == 1 && n > 0)
{
int arr[n];
arr[0] = 0;
for (i = 0; i<(n - 1); i++) {
arr[i + 1] = arr[i] + 10;
}
printf("%d", arr[3]);
for (i = 1; i < n; i += 4) {
l = arr[i] + l;
}
for (i = 2; i < n; i += 4) {
u = arr[i] + u;
}
for (i = 3; i < n; i += 4) {
m = arr[i] + m;
}
printf("\n%d\n", l);
printf("%d\n", u);
printf("%d\n", m);
printf("%d\n", d);
}
return 0;
}
See it live on ideone.com
I have a code that finds the sum of the divisors of a number, but I can't get it to apply on my increasing n and print all the numbers respectively.
The code is
long div(int n) {
long sum = 0;
int square_root = sqrt(n);
for (int i = 1; i <= square_root; i++) {
if (n % i == 0) {
sum += i;
if (i * i != n) {
sum += n / i;
}
}
}
return sum - n;
}
On my main() I need to have a c number that starts from 1 and goes to my MAXCYC which is 28. The n goes from 2 to MAXNUM which is 10000000. The program needs to find all perfect, amicable and sociable numbers and print them with their respective pairs.
Sample output:
Cycle of length 2: 12285 14595 12285
Cycle of length 5: 12496 14288 15472 14536 14264 12496
for (int n = 2; n <= MAXNUM; n++) {
long sum = div(n);
long res = div(sum);
if (res <= MAXNUM) { // Checking if the number is just sociable
int c = 0;
while (c <= MAXCYC && n != res) {
res = div(sum);
c++;
}
if (c <= MAXCYC) {
printf("Cycle of length %d: ", c);
printf("%ld ", sum);
do {
printf("%ld ", res);
res = div(res);
}
while (sum < res);
printf("%ld ", sum);
c += c - 2;
printf("\n");
}
}
}
I only get pairs of cycle length of 1, 2 and nothing above that. Also it doesn't even print it correctly since it says Cycle of length 0: in all of the results without increasing. I think the problem is in the f before the first print but I can't get it to work in a way that as long as my
(n == sum) it prints Cycle of length 1: x x pairs
(n == res && sum < res) it prints Cycle of length 2: x y x pairs
(res <= MAXNUM) it prints Cycle of length c: x y z ... x (c amount of pairs including first x)
What do you guys think I should change?
Ok, this code should work if I understood well your requirement.
#include <stdio.h>
#include <stdlib.h>
int div_sum(int n)
{
long sum = 0;
int square_root = sqrt(n);
for (int i = 1; i <= square_root; i++)
{
if (n % i == 0)
{
sum += i;
if (i * i != n)
{
sum += n / i;
}
}
}
return sum - n;
}
int MAX_N = 10000000;
int MAX_CYCLES = 28;
int main()
{
int cycles;
for(int n = 2; n < MAX_N; n++){
int found = 0;
for(int c = 1; !found && c <= MAX_CYCLES; c++){
cycles = c;
int aliquote = n;
while(cycles--) aliquote = div_sum(aliquote);
//it is a cycle of length c
cycles = c;
if(n == aliquote){
printf("Cycle of length %d: %d", c, n);
while(cycles--){
aliquote = div_sum(aliquote);
printf(" %d", aliquote);
}
printf("\n");
found = 1;
}
}
}
return 0;
}
I'm trying to create a program in C which, after every even number, will add a "0". But I have a problem. If I insert for example only even numbers (5 or more numbers) the program crashes.
Below is the program I have right now.
I would like some indications or a code sample to point out what I did wrong and how I can fix it.
void main()
{
int *a, i, n, m;
printf("dimensiune=");
scanf_s("%d", &n);
a = (int*)malloc(n*sizeof(int));
for (i = 0; i < n; i++)
{
printf("a[%d]=", i + 1);
scanf_s("%d", &a[i]);
}
for (i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
{
n++;
a = (int*)realloc(a, n*sizeof(int));
for (m = n - 1; m > i;m--)
{
a[m + 1] = a[m];
}
a[i + 1] = 0;
i++;
}
}
printf("\n currently you have %d numbers in this string\n", n);
printf("your string \n");
for (i = 0; i < n; i++)
{
printf("a[%d]=%d\n", i + 1, a[i]);
}
}
Change:
for (m = n - 1; m > i;m--)
{
a[m + 1] = a[m];
}
to:
for (m = n - 1; m > i;m--)
{
a[m] = a[m-1];
}
I've just tested it, it's working for me, should work for you.
I see a problem with this loop:
for (m = n - 1; m > i;m--)
{
a[m + 1] = a[m];
}
When you start the loop, n is the number of element in the loop. During the first iteration, m is the index of the last element of the loop. So, m+1 is after the last element, creating a buffer overflow.
Thanks for all comments I solved the bug replacing void main() with int main(void) + the solution provided by Shady Programmer.