George
George

Reputation: 1

My program works fine but does not return 0

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

int i,j;

void display_matrix(int matrix[],int rows,int colombs){
    for(i=0;i<rows;i++){
     for(j=0;j<colombs;j++)
        printf("%5d ",matrix[i*rows+j]);
    printf("\n");
    }
}

int *create_matrix(int rows,int colombs,int min,int max){
    int *matrix=NULL;
    matrix=(int*)calloc(colombs*rows,sizeof(int));
    for(i=0;i<rows;i++)
        for(j=0;j<colombs;j++)
            matrix[i*rows+j]=(rand()%(max-min+1))+min;
    
    return matrix;
}

int main(){
    
    int *m=NULL,row,col;
    
    do{
        printf("Give the number of rows:\n");
        scanf("%d",&row);
    }while(row<=0);
    
    do{
        printf("Give the number of colombs:\n");
        scanf("%d",&col);
    }while(col<=0);
    
    m=create_matrix(row,col,10,99);
    display_matrix(m,row,col);

    return 0;
}

The matrix is displayed as intended but the program return value is 3221226356. I tried changing the rows and colombs in the function create_matrix() and the return value was 0 but the matrix had trash data.

That is the result after i run the program: That is the result after i run the program

Upvotes: 0

Views: 97

Answers (1)

wohlstad
wohlstad

Reputation: 28409

It seems like you are using Windows.
On Windows error code 3221226356 (which is 0xc0000374 in hex) indicates a heap corruption.

The corruption is caused by writing to your matrix at an invalid index.

Your bug is in converting row and column indices to an index in matrix:

Instead of: i*rows+j
It should be: i*colombs+j
(since colombs is the stride of the matrix).

You have this bug in 2 places:

  1. When you print the matrix (in display_matrix):
    printf("%5d ",matrix[i*rows+j]);
    
    Should be:
    printf("%5d ",matrix[i*colombs+j]);
    
  2. When you fill the matrix (in create_matrix):
    matrix[i*rows+j]=(rand()%(max-min+1))+min;
    
    Should be:
    matrix[i*colombs+j]=(rand()%(max-min+1))+min;
    

A side note: colombs should be renamed to columns.

Upvotes: 2

Related Questions